using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Stores.Entities;
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 CreateStoreTableAreaCommandHandler(
    IStoreRepository storeRepository,
    ILogger<CreateStoreTableAreaCommandHandler> logger)
    : IRequestHandler<CreateStoreTableAreaCommand, StoreTableAreaDto>
{
    /// <inheritdoc />
    public async Task<StoreTableAreaDto> Handle(CreateStoreTableAreaCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId: null, cancellationToken);
        if (store is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        }
        var tenantId = store.TenantId;

        // 2. (空行后) 校验区域名称唯一
        var existingAreas = await storeRepository.GetTableAreasAsync(request.StoreId, tenantId, cancellationToken);
        var hasDuplicate = existingAreas.Any(x => x.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
        if (hasDuplicate)
        {
            throw new BusinessException(ErrorCodes.Conflict, "区域名称已存在");
        }

        // 3. (空行后) 构建实体并写入租户
        var area = new StoreTableArea
        {
            TenantId = tenantId,
            StoreId = request.StoreId,
            Name = request.Name.Trim(),
            Description = request.Description?.Trim(),
            SortOrder = request.SortOrder
        };

        // 4. (空行后) 持久化
        await storeRepository.AddTableAreasAsync(new[] { area }, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("创建桌台区域 {AreaId} 对应门店 {StoreId}", area.Id, request.StoreId);

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