using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Merchants.Entities;
using TakeoutSaaS.Domain.Merchants.Enums;
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 CreateStoreStaffCommandHandler(
    IMerchantRepository merchantRepository,
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<CreateStoreStaffCommandHandler> logger)
    : IRequestHandler<CreateStoreStaffCommand, StoreStaffDto>
{
    /// <inheritdoc />
    public async Task<StoreStaffDto> Handle(CreateStoreStaffCommand 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 staff = new MerchantStaff
        {
            MerchantId = store.MerchantId,
            StoreId = request.StoreId,
            Name = request.Name.Trim(),
            Phone = request.Phone.Trim(),
            Email = request.Email?.Trim(),
            RoleType = request.RoleType,
            Status = StaffStatus.Active
        };

        // 3. 持久化
        await merchantRepository.AddStaffAsync(staff, cancellationToken);
        await merchantRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("创建门店员工 {StaffId} 门店 {StoreId}", staff.Id, request.StoreId);

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