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 CreateStorePickupSlotCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<CreateStorePickupSlotCommandHandler> logger)
    : IRequestHandler<CreateStorePickupSlotCommand, StorePickupSlotDto>
{
    /// <inheritdoc />
    public async Task<StorePickupSlotDto> Handle(CreateStorePickupSlotCommand 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, "门店不存在");
        }

        // 2. 新建档期
        var slot = new StorePickupSlot
        {
            TenantId = tenantId,
            StoreId = request.StoreId,
            Name = request.Name.Trim(),
            StartTime = request.StartTime,
            EndTime = request.EndTime,
            CutoffMinutes = request.CutoffMinutes,
            Capacity = request.Capacity,
            ReservedCount = 0,
            Weekdays = request.Weekdays,
            IsEnabled = request.IsEnabled
        };
        await storeRepository.AddPickupSlotsAsync(new[] { slot }, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("创建自提档期 {SlotId} for store {StoreId}", slot.Id, request.StoreId);
        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
        };
    }
}
