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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 删除门店员工处理器。
/// </summary>
public sealed class DeleteStoreStaffCommandHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider,
    ILogger<DeleteStoreStaffCommandHandler> logger)
    : IRequestHandler<DeleteStoreStaffCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreStaffCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var staff = await merchantRepository.FindStaffByIdAsync(request.StaffId, tenantId, cancellationToken);
        if (staff is null || staff.StoreId != request.StoreId)
        {
            return false;
        }

        // 逻辑删除未定义，直接物理删除
        await merchantRepository.DeleteStaffAsync(staff.Id, tenantId, cancellationToken);
        await merchantRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除门店员工 {StaffId} 门店 {StoreId}", request.StaffId, request.StoreId);

        return true;
    }
}
