using Microsoft.EntityFrameworkCore;
using IamService.Domain.AggregatesModel.RoleAggregate;
using IamService.Domain.SeedWork;

namespace IamService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for ApplicationRole aggregate.
/// VI: Repository implementation cho ApplicationRole aggregate.
/// </summary>
public class RoleRepository : IRoleRepository
{
    private readonly IamServiceContext _context;

    public RoleRepository(IamServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public IUnitOfWork UnitOfWork => _context;

    /// <summary>
    /// EN: Find role by name.
    /// VI: Tìm role theo tên.
    /// </summary>
    public async Task<ApplicationRole?> FindByNameAsync(string name, CancellationToken cancellationToken = default)
    {
        return await _context.Roles
            .FirstOrDefaultAsync(r => r.NormalizedName == name.ToUpperInvariant(), cancellationToken);
    }

    /// <summary>
    /// EN: Find role by ID.
    /// VI: Tìm role theo ID.
    /// </summary>
    public async Task<ApplicationRole?> FindByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.Roles
            .FirstOrDefaultAsync(r => r.Id == id, cancellationToken);
    }

    /// <summary>
    /// EN: Get all roles.
    /// VI: Lấy tất cả roles.
    /// </summary>
    public async Task<IEnumerable<ApplicationRole>> GetAllAsync(CancellationToken cancellationToken = default)
    {
        return await _context.Roles
            .OrderBy(r => r.Name)
            .ToListAsync(cancellationToken);
    }

    /// <summary>
    /// EN: Add new role.
    /// VI: Thêm role mới.
    /// </summary>
    public ApplicationRole Add(ApplicationRole role)
    {
        return _context.Roles.Add(role).Entity;
    }

    /// <summary>
    /// EN: Update existing role.
    /// VI: Cập nhật role hiện có.
    /// </summary>
    public void Update(ApplicationRole role)
    {
        _context.Entry(role).State = EntityState.Modified;
    }

    /// <summary>
    /// EN: Delete role.
    /// VI: Xóa role.
    /// </summary>
    public void Delete(ApplicationRole role)
    {
        _context.Roles.Remove(role);
    }
}
