import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiConfigService } from '../../../core/services/api-config.service';
import {
    PermissionMatrixDto,
    UpdateRolePermissionsRequest,
} from '../../../core/models/permission.model';

/** Admin API for the configurable RBAC matrix (super_admin only on the server). */
@Injectable({ providedIn: 'root' })
export class PermissionApiService {
    private readonly endpoint: string;

    constructor(private http: HttpClient, apiConfig: ApiConfigService) {
        this.endpoint = apiConfig.getApiUrl('permissions');
    }

    /** GET /api/permissions — the full role × module matrix. */
    getMatrix(): Observable<PermissionMatrixDto> {
        return this.http.get<PermissionMatrixDto>(this.endpoint);
    }

    /** PUT /api/permissions/{roleName} — replaces a role's grants. */
    updateRole(roleName: string, request: UpdateRolePermissionsRequest): Observable<void> {
        return this.http.put<void>(`${this.endpoint}/${encodeURIComponent(roleName)}`, request);
    }
}
