using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
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 UpdateStoreTableAreaCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreTableAreaCommandHandler> logger)
    : IRequestHandler<UpdateStoreTableAreaCommand, StoreTableAreaDto?>
{
    /// <inheritdoc />
    public async Task<StoreTableAreaDto?> Handle(UpdateStoreTableAreaCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取区域
        var tenantId = tenantProvider.GetCurrentTenantId();
        var area = await storeRepository.FindTableAreaByIdAsync(request.AreaId, tenantId, cancellationToken);
        if (area is null)
        {
            return null;
        }

        // 2. 校验门店归属
        if (area.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "区域不属于该门店");
        }

        // 3. 名称唯一校验
        var areas = await storeRepository.GetTableAreasAsync(request.StoreId, tenantId, cancellationToken);
        var hasDuplicate = areas.Any(x => x.Id != request.AreaId && x.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
        if (hasDuplicate)
        {
            throw new BusinessException(ErrorCodes.Conflict, "区域名称已存在");
        }

        // 4. 更新字段
        area.Name = request.Name.Trim();
        area.Description = request.Description?.Trim();
        area.SortOrder = request.SortOrder;

        // 5. 持久化
        await storeRepository.UpdateTableAreaAsync(area, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新桌台区域 {AreaId} 对应门店 {StoreId}", area.Id, area.StoreId);

        // 6. 返回 DTO
        return StoreMapping.ToDto(area);
    }
}
