using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Stores.Entities;
using TakeoutSaaS.Domain.Stores.Enums;
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 CreateStoreHolidayCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<CreateStoreHolidayCommandHandler> logger)
    : IRequestHandler<CreateStoreHolidayCommand, StoreHolidayDto>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<CreateStoreHolidayCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<StoreHolidayDto> Handle(CreateStoreHolidayCommand 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, "门店不存在");
        }
        var storeTenantId = store.TenantId;

        // 2. 构建实体
        var holiday = new StoreHoliday
        {
            TenantId = storeTenantId,
            StoreId = request.StoreId,
            Date = NormalizeToUtc(request.Date),
            EndDate = request.EndDate.HasValue ? NormalizeToUtc(request.EndDate.Value) : null,
            IsAllDay = request.IsAllDay,
            StartTime = request.StartTime,
            EndTime = request.EndTime,
            OverrideType = request.OverrideType,
            IsClosed = request.OverrideType == OverrideType.Closed,
            Reason = request.Reason?.Trim()
        };

        // 3. 持久化
        await _storeRepository.AddHolidaysAsync(new[] { holiday }, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("创建节假日 {HolidayId} 对应门店 {StoreId}", holiday.Id, request.StoreId);

        // 4. 返回 DTO
        return StoreMapping.ToDto(holiday);
    }

    private static DateTime NormalizeToUtc(DateTime value)
    {
        return value.Kind switch
        {
            DateTimeKind.Utc => value,
            DateTimeKind.Local => value.ToUniversalTime(),
            _ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
        };
    }
}
