using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
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 UpdateStorePickupSlotCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStorePickupSlotCommandHandler> logger)
    : IRequestHandler<UpdateStorePickupSlotCommand, StorePickupSlotDto?>
{
    /// <inheritdoc />
    public async Task<StorePickupSlotDto?> Handle(UpdateStorePickupSlotCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询档期
        var tenantId = tenantProvider.GetCurrentTenantId();
        var slot = await storeRepository.FindPickupSlotByIdAsync(request.SlotId, tenantId, cancellationToken);
        if (slot is null || slot.StoreId != request.StoreId)
        {
            return null;
        }

        // 2. 更新字段
        slot.Name = request.Name.Trim();
        slot.StartTime = request.StartTime;
        slot.EndTime = request.EndTime;
        slot.CutoffMinutes = request.CutoffMinutes;
        slot.Capacity = request.Capacity;
        slot.Weekdays = request.Weekdays;
        slot.IsEnabled = request.IsEnabled;
        await storeRepository.UpdatePickupSlotAsync(slot, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新自提档期 {SlotId}", request.SlotId);
        return new StorePickupSlotDto
        {
            Id = slot.Id,
            StoreId = slot.StoreId,
            Name = slot.Name,
            StartTime = slot.StartTime,
            EndTime = slot.EndTime,
            CutoffMinutes = slot.CutoffMinutes,
            Capacity = slot.Capacity,
            ReservedCount = slot.ReservedCount,
            Weekdays = slot.Weekdays,
            IsEnabled = slot.IsEnabled
        };
    }
}
