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;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

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

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

        // 2. 构建实体
        var hour = new StoreBusinessHour
        {
            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);
    }
}
