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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 删除排班处理器。
/// </summary>
public sealed class DeleteStoreEmployeeShiftCommandHandler(
    IStoreRepository storeRepository,
    ILogger<DeleteStoreEmployeeShiftCommandHandler> logger)
    : IRequestHandler<DeleteStoreEmployeeShiftCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreEmployeeShiftCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取门店并解析租户
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId: null, cancellationToken);
        if (store is null)
        {
            return false;
        }
        var tenantId = store.TenantId;

        // 2. (空行后) 读取排班
        var shift = await storeRepository.FindShiftByIdAsync(request.ShiftId, tenantId, cancellationToken);
        if (shift is null || shift.StoreId != request.StoreId)
        {
            return false;
        }

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

        return true;
    }
}
