// app/core/services/role-state.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

export interface RoleUpdate {
  roleId: number;
  roleName: string;
  permissions: string[];
  timestamp: number;
}

@Injectable({
  providedIn: 'root'
})
export class RoleStateService {
  // Track when roles are updated
  private _roleUpdated = new BehaviorSubject<RoleUpdate | null>(null);
  public roleUpdated$ = this._roleUpdated.asObservable();

  // Track when a role is deleted
  private _roleDeleted = new BehaviorSubject<number | null>(null);
  public roleDeleted$ = this._roleDeleted.asObservable();

  // Track when a role is created
  private _roleCreated = new BehaviorSubject<RoleUpdate | null>(null);
  public roleCreated$ = this._roleCreated.asObservable();

  constructor() {
    console.log('✓ RoleStateService initialized');
  }

  /**
   * Notify that a role's permissions have been updated
   */
  notifyRoleUpdate(roleId: number, roleName: string, permissions: string[]): void {
    const update: RoleUpdate = {
      roleId,
      roleName,
      permissions,
      timestamp: Date.now()
    };
    
    console.log('📢 Role updated:', update);
    this._roleUpdated.next(update);
  }

  /**
   * Notify that a role has been deleted
   */
  notifyRoleDeleted(roleId: number): void {
    console.log('📢 Role deleted:', roleId);
    this._roleDeleted.next(roleId);
  }

  /**
   * Notify that a role has been created
   */
  notifyRoleCreated(roleId: number, roleName: string, permissions: string[]): void {
    const update: RoleUpdate = {
      roleId,
      roleName,
      permissions,
      timestamp: Date.now()
    };
    
    console.log('📢 Role created:', update);
    this._roleCreated.next(update);
  }

  /**
   * Clear all notifications
   */
  clear(): void {
    this._roleUpdated.next(null);
    this._roleDeleted.next(null);
    this._roleCreated.next(null);
  }
}