using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Merchants.Repositories;
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 UpdateStoreStaffCommandHandler(
    IMerchantRepository merchantRepository,
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreStaffCommandHandler> logger)
    : IRequestHandler<UpdateStoreStaffCommand, StoreStaffDto?>
{
    /// <inheritdoc />
    public async Task<StoreStaffDto?> Handle(UpdateStoreStaffCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验门店
        var tenantId = tenantProvider.GetCurrentTenantId();
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        if (store is null)
        {
            return null;
        }

        // 2. 读取员工
        var staff = await merchantRepository.FindStaffByIdAsync(request.StaffId, tenantId, cancellationToken);
        if (staff is null || staff.StoreId != request.StoreId)
        {
            return null;
        }

        // 3. 更新字段
        staff.Name = request.Name.Trim();
        staff.Phone = request.Phone.Trim();
        staff.Email = request.Email?.Trim();
        staff.RoleType = request.RoleType;
        staff.Status = request.Status;

        // 4. 持久化
        await merchantRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新门店员工 {StaffId} 门店 {StoreId}", staff.Id, staff.StoreId);

        // 5. 返回 DTO
        return StoreMapping.ToDto(staff);
    }
}
