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 UpdateStoreHolidayCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreHolidayCommandHandler> logger)
    : IRequestHandler<UpdateStoreHolidayCommand, StoreHolidayDto?>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<UpdateStoreHolidayCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<StoreHolidayDto?> Handle(UpdateStoreHolidayCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取配置
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _storeRepository.FindHolidayByIdAsync(request.HolidayId, tenantId, cancellationToken);
        if (existing is null)
        {
            return null;
        }

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

        // 3. 更新字段
        existing.Date = request.Date;
        existing.IsClosed = request.IsClosed;
        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);
    }
}
