// role.service.ts - NEW SERVICE FOR ROLE MANAGEMENT
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[]; // Array of permission IDs
  created_at: string;
  updated_at: 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) {
    // Load roles on service initialization
    this.loadRoles();
  }

  /**
   * Get all roles from backend
   */
  getRoles(): Observable<Role[]> {
    return this.http.get<Role[]>(this.apiUrl).pipe(
      tap(roles => {
        this._roles.next(roles);
      })
    );
  }

  /**
   * Load roles and cache them
   */
  loadRoles(): void {
    this.getRoles().subscribe(
      roles => console.log('Roles loaded:', roles.length),
      error => console.error('Error loading roles:', error)
    );
  }

  /**
   * 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).pipe(
      tap(() => this.loadRoles()) // Reload after creation
    );
  }

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

  /**
   * Delete role
   */
  deleteRole(id: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/${id}`).pipe(
      tap(() => this.loadRoles()) // Reload after deletion
    );
  }

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

  /**
   * Filter roles based on current user's role
   * Maintains the same permission logic
   */
  getAvailableRolesForUser(currentUserRole: string): Observable<Role[]> {
    return this.roles$.pipe(
      tap(roles => {
        let filteredRoles: Role[];
        
        if (currentUserRole === 'Client') {
          // Clients can only assign Refiller role
          filteredRoles = roles.filter(role => role.name === 'Refiller');
        } else if (['Management', 'SuperAdmin', 'Admin'].includes(currentUserRole)) {
          // Admins can assign any role
          filteredRoles = roles;
        } else {
          // Default - no roles available
          filteredRoles = [];
        }
        
        console.log(`Available roles for ${currentUserRole}:`, filteredRoles);
      })
    );
  }

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

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