using System.Linq;
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 UpdateStoreTableCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreTableCommandHandler> logger)
    : IRequestHandler<UpdateStoreTableCommand, StoreTableDto?>
{
    /// <inheritdoc />
    public async Task<StoreTableDto?> Handle(UpdateStoreTableCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取桌码
        var tenantId = tenantProvider.GetCurrentTenantId();
        var table = await storeRepository.FindTableByIdAsync(request.TableId, tenantId, cancellationToken);
        if (table is null)
        {
            return null;
        }

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

        // 3. 校验区域归属
        if (request.AreaId.HasValue)
        {
            var area = await storeRepository.FindTableAreaByIdAsync(request.AreaId.Value, tenantId, cancellationToken);
            if (area is null || area.StoreId != request.StoreId)
            {
                throw new BusinessException(ErrorCodes.ValidationFailed, "桌台区域不存在或不属于该门店");
            }
        }

        // 4. 校验桌码唯一
        var tables = await storeRepository.GetTablesAsync(request.StoreId, tenantId, cancellationToken);
        var exists = tables.Any(x => x.Id != request.TableId && x.TableCode.Equals(request.TableCode, StringComparison.OrdinalIgnoreCase));
        if (exists)
        {
            throw new BusinessException(ErrorCodes.Conflict, "桌码已存在");
        }

        // 5. 更新字段
        table.AreaId = request.AreaId;
        table.TableCode = request.TableCode.Trim();
        table.Capacity = request.Capacity;
        table.Tags = request.Tags?.Trim();
        table.Status = request.Status;

        // 6. 持久化
        await storeRepository.UpdateTableAsync(table, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新桌码 {TableId} 对应门店 {StoreId}", table.Id, table.StoreId);

        // 7. 返回 DTO
        return StoreMapping.ToDto(table);
    }
}
