import { SystemRole } from "./enums.js";

export const PermissionKey = {
  VIEW_PLANNING: "viewPlanning",
  VIEW_COSTS: "viewCosts",
  USE_ASSISTANT_ADVANCED_TOOLS: "useAssistantAdvancedTools",
  EXPORT_DATA: "exportData",
  IMPORT_DATA: "importData",
  APPROVE_VACATIONS: "approveVacations",
  MANAGE_BLUEPRINTS: "manageBlueprints",
  VIEW_ALL_RESOURCES: "viewAllResources",
  MANAGE_RESOURCES: "manageResources",
  MANAGE_PROJECTS: "manageProjects",
  MANAGE_ALLOCATIONS: "manageAllocations",
  MANAGE_ROLES: "manageRoles",
  MANAGE_USERS: "manageUsers",
  VIEW_SCORES: "viewScores",
} as const;

export type PermissionKey = (typeof PermissionKey)[keyof typeof PermissionKey];

export interface PermissionOverrides {
  granted?: PermissionKey[];
  denied?: PermissionKey[];
  chapterIds?: string[]; // wenn gesetzt: Manager sieht nur diese Chapters
}

// Default-Permissions pro SystemRole
export const ROLE_DEFAULT_PERMISSIONS: Record<SystemRole, PermissionKey[]> = {
  ADMIN: Object.values(PermissionKey),
  MANAGER: [
    PermissionKey.VIEW_PLANNING,
    PermissionKey.VIEW_COSTS,
    PermissionKey.EXPORT_DATA,
    PermissionKey.IMPORT_DATA,
    PermissionKey.APPROVE_VACATIONS,
    PermissionKey.VIEW_ALL_RESOURCES,
    PermissionKey.MANAGE_RESOURCES,
    PermissionKey.MANAGE_PROJECTS,
    PermissionKey.MANAGE_ALLOCATIONS,
    PermissionKey.MANAGE_ROLES,
    PermissionKey.VIEW_SCORES,
  ],
  CONTROLLER: [
    PermissionKey.VIEW_PLANNING,
    PermissionKey.VIEW_COSTS,
    PermissionKey.EXPORT_DATA,
    PermissionKey.VIEW_ALL_RESOURCES,
  ],
  USER: [],
  VIEWER: [],
};

export function resolvePermissions(
  systemRole: SystemRole,
  overrides?: PermissionOverrides | null,
  /** Optional DB-based defaults per role. If provided, takes precedence over ROLE_DEFAULT_PERMISSIONS. */
  roleDefaults?: Record<string, PermissionKey[]>,
): Set<PermissionKey> {
  const defaults = roleDefaults?.[systemRole] ?? ROLE_DEFAULT_PERMISSIONS[systemRole] ?? [];
  const base = new Set<PermissionKey>(defaults);
  if (overrides?.granted) {
    for (const p of overrides.granted) base.add(p);
  }
  if (overrides?.denied) {
    for (const p of overrides.denied) base.delete(p);
  }
  return base;
}

export function hasPermission(
  permissions: Set<PermissionKey>,
  key: PermissionKey
): boolean {
  return permissions.has(key);
}
