using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.SystemParameters.Commands;
using TakeoutSaaS.Application.App.SystemParameters.Dto;
using TakeoutSaaS.Domain.SystemParameters.Entities;
using TakeoutSaaS.Domain.SystemParameters.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.SystemParameters.Handlers;

/// <summary>
/// 创建系统参数命令处理器。
/// </summary>
public sealed class CreateSystemParameterCommandHandler(
    ISystemParameterRepository repository,
    ILogger<CreateSystemParameterCommandHandler> logger)
    : IRequestHandler<CreateSystemParameterCommand, SystemParameterDto>
{
    private readonly ISystemParameterRepository _repository = repository;
    private readonly ILogger<CreateSystemParameterCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<SystemParameterDto> Handle(CreateSystemParameterCommand request, CancellationToken cancellationToken)
    {
        // 1. 唯一性校验
        var existing = await _repository.FindByKeyAsync(request.Key, cancellationToken);
        if (existing != null)
        {
            throw new BusinessException(ErrorCodes.Conflict, "系统参数键已存在");
        }

        // 2. 构建实体
        var parameter = new SystemParameter
        {
            Key = request.Key.Trim(),
            Value = request.Value.Trim(),
            Description = request.Description?.Trim(),
            SortOrder = request.SortOrder,
            IsEnabled = request.IsEnabled
        };

        // 3. 持久化
        await _repository.AddAsync(parameter, cancellationToken);
        await _repository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("创建系统参数 {Key}", parameter.Key);

        // 4. 映射返回
        return MapToDto(parameter);
    }

    private static SystemParameterDto MapToDto(SystemParameter parameter) => new()
    {
        Id = parameter.Id,
        TenantId = parameter.TenantId,
        Key = parameter.Key,
        Value = parameter.Value,
        Description = parameter.Description,
        SortOrder = parameter.SortOrder,
        IsEnabled = parameter.IsEnabled,
        CreatedAt = parameter.CreatedAt,
        UpdatedAt = parameter.UpdatedAt
    };
}
