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;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 更新桌台区域处理器。
/// </summary>
public sealed class UpdateStoreTableAreaCommandHandler(
    IStoreRepository storeRepository,
    ILogger<UpdateStoreTableAreaCommandHandler> logger)
    : IRequestHandler<UpdateStoreTableAreaCommand, StoreTableAreaDto?>
{
    /// <inheritdoc />
    public async Task<StoreTableAreaDto?> Handle(UpdateStoreTableAreaCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取门店并解析租户
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId: null, cancellationToken);
        if (store is null)
        {
            return null;
        }
        var tenantId = store.TenantId;

        // 2. (空行后) 读取区域
        var area = await storeRepository.FindTableAreaByIdAsync(request.AreaId, tenantId, cancellationToken);
        if (area is null)
        {
            return null;
        }

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

        // 4. (空行后) 名称唯一校验
        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, "区域名称已存在");
        }

        // 5. (空行后) 更新字段
        area.Name = request.Name.Trim();
        area.Description = request.Description?.Trim();
        area.SortOrder = request.SortOrder;

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

        // 7. (空行后) 返回 DTO
        return StoreMapping.ToDto(area);
    }
}
