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

        // 2. 校验门店归属
        if (area.StoreId != request.StoreId)
        {
            return false;
        }

        // 3. 校验区域下无桌码
        var tables = await storeRepository.GetTablesAsync(request.StoreId, tenantId, cancellationToken);
        var hasTable = tables.Any(x => x.AreaId == request.AreaId);
        if (hasTable)
        {
            throw new BusinessException(ErrorCodes.Conflict, "区域下仍有桌码，无法删除");
        }

        // 4. 删除
        await storeRepository.DeleteTableAreaAsync(request.AreaId, tenantId, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除桌台区域 {AreaId} 对应门店 {StoreId}", request.AreaId, request.StoreId);

        return true;
    }
}
