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.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 UpdateStoreHolidayCommandHandler(
    IStoreRepository storeRepository,
    ILogger<UpdateStoreHolidayCommandHandler> logger)
    : IRequestHandler<UpdateStoreHolidayCommand, StoreHolidayDto?>
{
    /// <inheritdoc />
    public async Task<StoreHolidayDto?> Handle(UpdateStoreHolidayCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取配置
        var existing = await storeRepository.FindHolidayByIdAsync(request.HolidayId, null, cancellationToken);
        if (existing is null)
        {
            return null;
        }

        // 2. 校验门店归属
        if (existing.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "节假日配置不属于该门店");
        }

        // 3. 更新字段
        existing.Date = NormalizeToUtc(request.Date);
        existing.EndDate = request.EndDate.HasValue ? NormalizeToUtc(request.EndDate.Value) : null;
        existing.IsAllDay = request.IsAllDay;
        existing.StartTime = request.StartTime;
        existing.EndTime = request.EndTime;
        existing.OverrideType = request.OverrideType;
        existing.IsClosed = request.OverrideType == OverrideType.Closed;
        existing.Reason = request.Reason?.Trim();

        // 4. 持久化
        await storeRepository.UpdateHolidayAsync(existing, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新节假日 {HolidayId} 对应门店 {StoreId}", existing.Id, existing.StoreId);

        // 5. 返回 DTO
        return StoreMapping.ToDto(existing);
    }

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