using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 删除排班处理器。
/// </summary>
public sealed class DeleteStoreEmployeeShiftCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<DeleteStoreEmployeeShiftCommandHandler> logger)
    : IRequestHandler<DeleteStoreEmployeeShiftCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreEmployeeShiftCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取排班
        var tenantId = tenantProvider.GetCurrentTenantId();
        var shift = await storeRepository.FindShiftByIdAsync(request.ShiftId, tenantId, cancellationToken);
        if (shift is null || shift.StoreId != request.StoreId)
        {
            return false;
        }

        // 2. 删除
        await storeRepository.DeleteShiftAsync(request.ShiftId, tenantId, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除排班 {ShiftId} 门店 {StoreId}", request.ShiftId, request.StoreId);

        return true;
    }
}
