using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Domain.Identity.Entities;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 创建角色模板处理器。
/// </summary>
public sealed class CreateRoleTemplateCommandHandler(IRoleTemplateRepository roleTemplateRepository)
    : IRequestHandler<CreateRoleTemplateCommand, RoleTemplateDto>
{
    /// <inheritdoc />
    public async Task<RoleTemplateDto> Handle(CreateRoleTemplateCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验必填
        if (string.IsNullOrWhiteSpace(request.TemplateCode) || string.IsNullOrWhiteSpace(request.Name))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "模板编码与名称不能为空");
        }

        // 2. 检查编码唯一
        var existing = await roleTemplateRepository.FindByCodeAsync(request.TemplateCode, cancellationToken);
        if (existing != null)
        {
            throw new BusinessException(ErrorCodes.Conflict, $"模板编码 {request.TemplateCode} 已存在");
        }

        // 3. 构建模板实体
        var template = new RoleTemplate
        {
            TemplateCode = request.TemplateCode.Trim(),
            Name = request.Name.Trim(),
            Description = request.Description,
            IsActive = request.IsActive
        };

        // 4. 清洗权限编码
        var permissions = request.PermissionCodes
            .Where(code => !string.IsNullOrWhiteSpace(code))
            .Select(code => code.Trim())
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToArray();

        // 5. 持久化并返回 DTO
        await roleTemplateRepository.AddAsync(template, permissions, cancellationToken);
        await roleTemplateRepository.SaveChangesAsync(cancellationToken);

        return TemplateMapper.ToDto(template, permissions);
    }
}
