import { Component, OnInit } from '@angular/core';
import { BaseService } from 'src/app/shared/service/base.service';

interface Role {
  id: number;
  name: string;
  description?: string;
}

interface Permission {
  id: number;
  code: string;
  label: string;
  module: string;
}

@Component({
  selector: 'app-rbac-management',
  templateUrl: './rbac-management.component.html',
   styleUrls: ['./rbac-management.component.scss'],
})
export class RbacManagementComponent implements OnInit {

  roles: Role[] = [];
  permissions: Permission[] = [];
userRole;
visibleRoles;
  showRoleDialog = false;
  showPermDialog = false;

  newRole: Role = { id: 0, name: '', description: '' };
  newPerm: Permission = { id: 0, code: '', label: '', module: '' };

  matrix: { roleId: number, permissionId: number }[] = [];
  roleSearch = '';
permSearch = '';
matrixSearch = '';

constructor (private baseService:BaseService){

}

  ngOnInit() {
    this.loadMatrix();
     this.userRole = sessionStorage.getItem('role') || '';

  }

setVisibleRoles() {
  this.visibleRoles = this.getVisibleRoles();
  console.log(this.visibleRoles);
  
}
  getVisibleRoles() {
  if (!this.roles || this.roles.length === 0) return [];

  return this.roles.filter(role => {
    if (!role || !role.name) return false; // ❌ remove empty role

    // hide logged-in role
    if (role.name === this.userRole) return false;

    // special rule
    if (this.userRole === 'LIBRARIAN') {
      return role.name === 'ADMIN' || role.name === 'LIBRARIAN';
    }

    return true;
  });
}
  loadMatrix() {
  this.baseService.getData('roles/matrix').subscribe((res: any) => {

    const data = res.data;

    this.roles = data.roles;
    this.permissions = data.permissions;
    this.matrix = data.assignments;
     this.setVisibleRoles();

  });
}
loadRoles() {
  this.baseService.getData('roles').subscribe((res: any) => {
    this.roles = res.data || [];
  });
}
loadPermissions() {
  this.baseService.getData('permissions').subscribe((res: any) => {
    this.permissions = res.data || [];
  });
}
deleteRole(role: any) {
  console.log(role);
  
  if (confirm(`Delete role "${role.name}"?`)) {
    this.roles = this.roles.filter(r => r !== role);
this.baseService.deleteData(`roles/${role.id}`)
    .subscribe(() => {this.loadRoles(); this.loadMatrix()});
    // 🔥 if API call needed:
    // this.roleService.delete(role.id).subscribe(() => this.loadRoles());
  }
}
 addRole() {
  if (!this.newRole.name.trim()) return;

  const payload = {
    name: this.newRole.name,
    description: this.newRole.description
  };

  this.baseService.postData('roles', new URLSearchParams(payload))
    .subscribe(() => {
      this.showRoleDialog = false;
      this.newRole = { id: 0, name: '', description: '' };
      this.loadRoles(); // refresh
      this.loadMatrix();
    });
}



  addPermission() {
  if (!this.newPerm.code.trim()) return;

  const payload = {
    code: this.newPerm.code,
    label: this.newPerm.label,
    module: this.newPerm.module
  };

  this.baseService.postData('permissions', payload)
    .subscribe(() => {
      this.showPermDialog = false;
      this.newPerm = { id: 0, code: '', label: '', module: '' };
      this.loadPermissions();
    });
}
deletePermission(id: number) {
  this.baseService.deleteData(`permissions/${id}`)
    .subscribe(() => this.loadPermissions());
}
toggle(roleId: number, permissionId: number) {

  if (this.has(roleId, permissionId)) {

    this.baseService.deleteData(`roles/${roleId}/permissions/${permissionId}`)
      .subscribe(() => this.loadMatrix());

  } else {

    this.baseService.postData(`roles/${roleId}/permissions/${permissionId}`, {})
      .subscribe(() => this.loadMatrix());
  }
}

has(roleId: number, permissionId: number): boolean {
  return this.matrix.some(
    m => m.roleId === roleId && m.permissionId === permissionId
  );
}
}
