using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Stores.Entities;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 创建营业时段处理器。
/// </summary>
public sealed class CreateStoreBusinessHourCommandHandler(
    IStoreRepository storeRepository,
    ILogger<CreateStoreBusinessHourCommandHandler> logger)
    : IRequestHandler<CreateStoreBusinessHourCommand, StoreBusinessHourDto>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ILogger<CreateStoreBusinessHourCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<StoreBusinessHourDto> Handle(CreateStoreBusinessHourCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var store = await _storeRepository.FindByIdAsync(request.StoreId, tenantId: null, cancellationToken);
        if (store is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        }
        var tenantId = store.TenantId;

        // 2. (空行后) 构建实体并写入租户
        var hour = new StoreBusinessHour
        {
            TenantId = tenantId,
            StoreId = request.StoreId,
            DayOfWeek = request.DayOfWeek,
            HourType = request.HourType,
            StartTime = request.StartTime,
            EndTime = request.EndTime,
            CapacityLimit = request.CapacityLimit,
            Notes = request.Notes?.Trim()
        };

        // 3. (空行后) 持久化
        await _storeRepository.AddBusinessHoursAsync(new[] { hour }, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("创建营业时段 {BusinessHourId} 对应门店 {StoreId}", hour.Id, request.StoreId);

        // 4. (空行后) 返回 DTO
        return StoreMapping.ToDto(hour);
    }
}
