// role-management.service.ts - COMPLETE SERVICE
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';
import { environment } from '@environments/environment';

export interface Permission {
  id: string;
  name: string;
  description: string;
  module: string;
}

export interface Role {
  id: number;
  name: string;
  description: string;
  permissions: string[];
  created_at: string;
  updated_at: string;
  created_by?: number;
  created_by_username?: string;
}

@Injectable({
  providedIn: 'root'
})
export class RoleService {
  private apiUrl = `${environment.apiUrl}/roles`;
  private permissionsUrl = `${environment.apiUrl}/permissions`;
  
  // Cache roles to avoid repeated API calls
  private _roles: BehaviorSubject<Role[]> = new BehaviorSubject<Role[]>([]);
  public roles$ = this._roles.asObservable();

  constructor(private http: HttpClient) {
    console.log('✓ RoleService initialized');
  }

  /**
   * Get all roles from backend
   */
  getRoles(): Observable<Role[]> {
    return this.http.get<Role[]>(this.apiUrl).pipe(
      tap(roles => {
        this._roles.next(roles);
        console.log('✓ Roles cached:', roles.length);
      })
    );
  }

  /**
   * Get single role by ID
   */
  getRole(id: number): Observable<Role> {
    return this.http.get<Role>(`${this.apiUrl}/${id}`);
  }

  /**
   * Create new role
   */
  createRole(role: Partial<Role>): Observable<Role> {
    return this.http.post<Role>(this.apiUrl, role);
  }

  /**
   * Update existing role
   */
  updateRole(id: number, role: Partial<Role>): Observable<Role> {
    return this.http.put<Role>(`${this.apiUrl}/${id}`, role);
  }

  /**
   * Delete role
   */
  deleteRole(id: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }

  /**
   * Get all available permissions
   */
  getPermissions(): Observable<Permission[]> {
    return this.http.get<Permission[]>(this.permissionsUrl);
  }

  /**
   * Convert Role array to dropdown format
   */
  rolesToDropdownFormat(roles: Role[]): { value: string; label: string }[] {
    return roles.map(role => ({
      value: role.name,
      label: role.name
    }));
  }

  /**
   * Get role by name from cached roles
   */
  getRoleByName(name: string): Role | undefined {
    return this._roles.getValue().find(role => role.name === name);
  }

  /**
   * Get current cached roles
   */
  getCachedRoles(): Role[] {
    return this._roles.getValue();
  }

  /**
   * Clear cached roles
   */
  clearCache(): void {
    this._roles.next([]);
  }
}