using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace IamService.Infrastructure.Authorization;

/// <summary>
/// EN: Extension methods for configuring Authorization Policies.
/// VI: Các extension methods để cấu hình Authorization Policies.
/// </summary>
public static class AuthorizationExtensions
{
    /// <summary>
    /// EN: Add authorization policies for IAM Service.
    /// VI: Thêm authorization policies cho IAM Service.
    /// </summary>
    /// <param name="services">Service collection / Service collection</param>
    /// <returns>Service collection with authorization policies / Service collection với authorization policies</returns>
    public static IServiceCollection AddAuthorizationPolicies(this IServiceCollection services)
    {
        services.AddAuthorizationBuilder()
            // EN: SuperAdmin - Full system access
            // VI: SuperAdmin - Quyền truy cập toàn hệ thống
            .AddPolicy("RequireSuperAdmin", policy =>
                policy.RequireRole("SuperAdmin"))

            // EN: Admin - Platform management (SuperAdmin or Admin)
            // VI: Admin - Quản lý platform (SuperAdmin hoặc Admin)
            .AddPolicy("RequireAdmin", policy =>
                policy.RequireRole("SuperAdmin", "Admin"))

            // EN: Auditor - Read-only audit access
            // VI: Auditor - Quyền xem audit logs
            .AddPolicy("RequireAuditor", policy =>
                policy.RequireRole("SuperAdmin", "Admin", "Auditor"))

            // EN: OwnerOrAdmin - user accessing own resource or Admin/SuperAdmin
            // VI: OwnerOrAdmin - user truy cập resource của mình hoặc Admin/SuperAdmin
            .AddPolicy("OwnerOrAdmin", policy =>
                policy.Requirements.Add(new OwnerOrAdminRequirement()));

        // EN: Register custom authorization handler for OwnerOrAdmin policy
        // VI: Đăng ký custom authorization handler cho policy OwnerOrAdmin
        services.AddScoped<IAuthorizationHandler, OwnerOrAdminHandler>();

        return services;
    }
}
