import { AbilityBuilder, PureAbility } from '@casl/ability';

// The actions map directly to the Permission type used in your role_permissions table
export type AppAction = 'view' | 'create' | 'edit' | 'delete' | 'manage';

// The subjects map to the page names stored in the role_permissions table
export type AppSubject =
  | 'My Properties'
  | 'Home Page'
  | 'About Us Page'
  | 'FAQ Page'
  | 'Property Data'
  | 'Header Images'
  | 'Login Page'
  | 'Inquiries & Leads'
  | 'User Management'
  | 'Content Management'
  | 'Overview'
  | 'Optimizations'
  | 'all';

export type AppAbility = PureAbility<[AppAction, AppSubject]>;

export type PagePermissions = {
  [page: string]: ('view' | 'create' | 'edit' | 'delete')[];
};

/**
 * Build a CASL Ability from the user's role and their page-level permissions
 * fetched from the role_permissions table.
 */
export function defineAbilityFor(role: string, permissions: PagePermissions): AppAbility {
  const { can, build } = new AbilityBuilder<AppAbility>(PureAbility);

  const normalizedRole = role.toLowerCase();

  // Admin and developer get full access to everything
  if (normalizedRole === 'admin' || normalizedRole === 'developer') {
    can('manage', 'all');
  }

  // Everyone can view the Overview page
  can('view', 'Overview');

  // Apply page-level permissions from the database
  for (const [page, actions] of Object.entries(permissions)) {
    for (const action of actions) {
      can(action, page as AppSubject);
    }
  }

  // Optimizations page is developer-only (already covered by 'manage all' above,
  // but explicit for clarity — non-admin/non-developer users will never have this)
  if (normalizedRole === 'developer') {
    can('manage', 'Optimizations');
  }

  return build();
}
