using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Domain.Identity.Entities;
using TakeoutSaaS.Domain.Identity.Enums;
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 CreateAdminRoleCommandHandler(IRoleRepository roleRepository)
    : IRequestHandler<CreateAdminRoleCommand, RoleDto>
{
    /// <inheritdoc />
    public async Task<RoleDto> Handle(CreateAdminRoleCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验必填字段
        if (string.IsNullOrWhiteSpace(request.Code) || string.IsNullOrWhiteSpace(request.Name))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "角色编码与名称不能为空");
        }

        // 2. 检查编码唯一性（平台范围内）
        var existing = await roleRepository.FindByCodeAsync(PortalType.Admin, null, request.Code, cancellationToken);
        if (existing is not null)
        {
            throw new BusinessException(ErrorCodes.Conflict, $"角色编码 {request.Code} 已存在");
        }

        // 3. 构建角色实体
        var role = new Role
        {
            Portal = PortalType.Admin,
            TenantId = null,
            Code = request.Code.Trim(),
            Name = request.Name.Trim(),
            Description = request.Description
        };

        // 4. 持久化
        await roleRepository.AddAsync(role, cancellationToken);
        await roleRepository.SaveChangesAsync(cancellationToken);

        // 5. 返回 DTO
        return new RoleDto
        {
            Portal = role.Portal,
            Id = role.Id,
            TenantId = role.TenantId,
            Code = role.Code,
            Name = role.Name,
            Description = role.Description
        };
    }
}
