/** TP staff role templates: permission subsets applied on top of project role `tp`. */

export const TP_STAFF_ROLES = [
  "tp_org_admin",
  "tp_site_lead",
  "tp_attendance_clerk",
  "tp_outcomes_officer",
  "tp_readonly",
] as const;

export type TpStaffRole = (typeof TP_STAFF_ROLES)[number];

export const TP_STAFF_ROLE_LABELS: Record<TpStaffRole, string> = {
  tp_org_admin: "Organization admin",
  tp_site_lead: "Site lead",
  tp_attendance_clerk: "Attendance clerk",
  tp_outcomes_officer: "Outcomes officer",
  tp_readonly: "Read-only viewer",
};

/** Base TP permissions from seed; org admin adds manage:tp-staff. */
const TP_ORG_ADMIN_EXTRA = ["manage:tp-staff"] as const;

const TP_SITE_LEAD: readonly string[] = [
  "view:dashboard",
  "view:providers",
  "view:trainings",
  "view:trainees",
  "import:trainees",
  "create:trainees",
  "edit:trainees",
  "view:attendance",
  "submit:attendance",
  "view:activities",
  "submit:activity",
  "submit:outcomes",
  "view:indicators",
  "view:feedback",
  "respond:feedback",
  "resolve:feedback",
  "request:training-breakdowns",
];

const TP_ATTENDANCE_CLERK: readonly string[] = [
  "view:dashboard",
  "view:trainings",
  "view:trainees",
  "view:attendance",
  "submit:attendance",
];

const TP_OUTCOMES_OFFICER: readonly string[] = [
  "view:dashboard",
  "view:trainings",
  "view:trainees",
  "submit:outcomes",
  "view:indicators",
  "submit:claims",
];

const TP_READONLY: readonly string[] = [
  "view:dashboard",
  "view:providers",
  "view:trainings",
  "view:trainees",
  "view:attendance",
  "view:activities",
  "view:indicators",
  "view:feedback",
];

/** When staffRole is tp_org_admin, caller should pass full TP role permissions + extras. */
export function permissionsForTpStaffRole(staffRole: string, baseTpAbilities: string[]): string[] {
  if (staffRole === "tp_org_admin") {
    const set = new Set(baseTpAbilities);
    for (const k of TP_ORG_ADMIN_EXTRA) set.add(k);
    return [...set];
  }
  const map: Record<string, readonly string[]> = {
    tp_site_lead: TP_SITE_LEAD,
    tp_attendance_clerk: TP_ATTENDANCE_CLERK,
    tp_outcomes_officer: TP_OUTCOMES_OFFICER,
    tp_readonly: TP_READONLY,
  };
  const template = map[staffRole];
  if (!template) return baseTpAbilities;
  const base = new Set(baseTpAbilities);
  return template.filter((k) => base.has(k));
}

export function isTpStaffRole(value: string): value is TpStaffRole {
  return (TP_STAFF_ROLES as readonly string[]).includes(value);
}
