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;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

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

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

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

        // 4. (空行后) 校验区域下无桌码
        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, "区域下仍有桌码，无法删除");
        }

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

        return true;
    }
}
