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;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 创建节假日配置处理器。
/// </summary>
public sealed class CreateStoreHolidayCommandHandler(
    IStoreRepository storeRepository,
    ILogger<CreateStoreHolidayCommandHandler> logger)
    : IRequestHandler<CreateStoreHolidayCommand, StoreHolidayDto>
{
    /// <inheritdoc />
    public async Task<StoreHolidayDto> Handle(CreateStoreHolidayCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var store = await storeRepository.FindByIdAsync(request.StoreId, null, 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)
        };
    }
}
