import type { PrismaClient } from "@prisma/client";

/** Permissions added after initial deploy — upsert definition only; grant role links if missing (never revoke). */
const APPEND_ONLY_PERMISSIONS: Array<{
  key: string;
  label: string;
  category: string;
  description?: string;
  grantToRoleCodes: readonly string[];
}> = [
  {
    key: "admin:purge-training",
    label: "Purge training and scoped data",
    category: "admin",
    description: "Permanently delete a training and all trainees, cohorts, batches, attendance, and related records.",
    grantToRoleCodes: ["admin"],
  },
  {
    key: "manage:tp-staff",
    label: "Manage TP staff accounts",
    category: "providers",
    description: "Invite and manage scoped staff accounts for a training provider organization.",
    grantToRoleCodes: ["admin", "me"],
  },
  {
    key: "review:trainee-duplicates",
    label: "Review possible duplicate trainees",
    category: "trainees",
    description: "Run duplicate detection scans and review or dismiss possible duplicate trainee pairs.",
    grantToRoleCodes: ["admin", "me"],
  },
  {
    key: "delete:trainees",
    label: "Delete trainees",
    category: "trainees",
    description: "Permanently delete trainee records (admin only).",
    grantToRoleCodes: ["admin"],
  },
  {
    key: "admin:phone-correction",
    label: "Correct trainee phone numbers",
    category: "admin",
    description: "Fix trainee phones corrupted by scientific notation in CSV exports.",
    grantToRoleCodes: ["admin"],
  },
];

/**
 * Append new permission definitions and grant them to listed roles when not already present.
 * Does not remove or change existing role_permission rows (including custom denials).
 */
export async function ensureAppendOnlyPermissions(prisma: PrismaClient): Promise<void> {
  for (const def of APPEND_ONLY_PERMISSIONS) {
    const permission = await prisma.permission.upsert({
      where: { key: def.key },
      create: {
        key: def.key,
        label: def.label,
        category: def.category,
        description: def.description ?? null,
      },
      update: {
        label: def.label,
        category: def.category,
        description: def.description ?? null,
      },
      select: { id: true },
    });

    for (const roleCode of def.grantToRoleCodes) {
      const role = await prisma.role.findUnique({
        where: { code: roleCode },
        select: { id: true },
      });
      if (!role) continue;

      const existing = await prisma.rolePermission.findUnique({
        where: { roleId_permissionId: { roleId: role.id, permissionId: permission.id } },
        select: { id: true },
      });
      if (existing) continue;

      await prisma.rolePermission.create({
        data: { roleId: role.id, permissionId: permission.id, allowed: true },
      });
    }
  }
}
