import type { PrismaClient } from "@prisma/client";
import { z } from "zod";
import { isTpStaffRole } from "./tpStaffRoleTemplates.js";

export const deliveryScopeInputSchema = z.discriminatedUnion("level", [
  z.object({ level: z.literal("provider") }),
  z.object({
    level: z.literal("cohort"),
    trainingId: z.string().regex(/^\d+$/),
    cohortId: z.string().regex(/^\d+$/),
  }),
  z.object({
    level: z.literal("batch"),
    trainingId: z.string().regex(/^\d+$/),
    batchId: z.string().regex(/^\d+$/),
  }),
]);

export type DeliveryScopeInput = z.infer<typeof deliveryScopeInputSchema>;

export async function validateDeliveryScopes(
  db: PrismaClient,
  projectId: bigint,
  trainingProviderId: bigint,
  scopes: DeliveryScopeInput[],
): Promise<
  Array<{
    scopeLevel: string;
    trainingId: bigint | null;
    cohortId: bigint | null;
    batchId: bigint | null;
  }>
> {
  if (!scopes.length) throw Object.assign(new Error("At least one delivery scope is required."), { status: 422 });

  const normalized: Array<{
    scopeLevel: string;
    trainingId: bigint | null;
    cohortId: bigint | null;
    batchId: bigint | null;
  }> = [];

  for (const s of scopes) {
    if (s.level === "provider") {
      normalized.push({ scopeLevel: "provider", trainingId: null, cohortId: null, batchId: null });
      continue;
    }
    const trainingId = BigInt(s.trainingId);
    const training = await db.training.findFirst({
      where: { id: trainingId, projectId, trainingProviderId },
      select: { id: true },
    });
    if (!training) {
      throw Object.assign(new Error("Training not found for this provider."), { status: 422 });
    }
    if (s.level === "cohort") {
      const cohortId = BigInt(s.cohortId);
      const cohort = await db.trainingCohort.findFirst({
        where: { id: cohortId, projectId, trainingId, trainingProviderId },
        select: { id: true },
      });
      if (!cohort) throw Object.assign(new Error("Cohort not found for this training."), { status: 422 });
      normalized.push({ scopeLevel: "cohort", trainingId, cohortId, batchId: null });
      continue;
    }
    const batchId = BigInt(s.batchId);
    const batch = await db.trainingBatch.findFirst({
      where: { id: batchId, projectId, trainingId, trainingProviderId },
      select: { id: true, cohortId: true },
    });
    if (!batch) throw Object.assign(new Error("Delivery batch not found for this training."), { status: 422 });
    normalized.push({
      scopeLevel: "batch",
      trainingId,
      cohortId: batch.cohortId,
      batchId,
    });
  }
  return normalized;
}

export function parseStaffRole(raw: string) {
  if (!isTpStaffRole(raw)) {
    throw Object.assign(new Error("Invalid staff role."), { status: 422 });
  }
  return raw;
}

export async function ensureTpOrgAdminOrProjectAdmin(
  db: PrismaClient,
  projectId: bigint,
  userId: bigint,
  trainingProviderId: bigint,
): Promise<void> {
  const adminMembership = await db.projectUser.findFirst({
    where: { projectId, userId, projectRole: { in: ["admin", "me"] } },
    include: {
      role: {
        include: {
          rolePermissions: {
            where: { allowed: true, permission: { key: "manage:tps" } },
            select: { id: true },
          },
        },
      },
    },
  });
  if ((adminMembership?.role?.rolePermissions.length ?? 0) > 0) return;

  const owner = await db.trainingProvider.findFirst({
    where: { projectId, id: trainingProviderId, userId },
    select: { id: true },
  });
  if (owner) return;

  const staffAdmin = await db.tpStaffMembership.findFirst({
    where: {
      projectId,
      trainingProviderId,
      userId,
      isActive: true,
      staffRole: "tp_org_admin",
    },
    select: { id: true },
  });
  if (staffAdmin) return;

  throw Object.assign(new Error("Only TP organization admins can manage staff."), { status: 403 });
}

export async function formatScopeSummary(
  db: PrismaClient,
  scopes: Array<{
    scopeLevel: string;
    trainingId: bigint | null;
    cohortId: bigint | null;
    batchId: bigint | null;
  }>,
): Promise<string[]> {
  const lines: string[] = [];
  for (const s of scopes) {
    if (s.scopeLevel === "provider") {
      lines.push("All sites (provider-wide)");
      continue;
    }
    if (s.scopeLevel === "cohort" && s.cohortId) {
      const c = await db.trainingCohort.findUnique({
        where: { id: s.cohortId },
        select: { name: true, code: true, location: { select: { name: true } } },
      });
      lines.push(c ? `${c.location?.name ?? c.name} (${c.code}) — all campuses` : `Cohort ${s.cohortId}`);
      continue;
    }
    if (s.scopeLevel === "batch" && s.batchId) {
      const b = await db.trainingBatch.findUnique({
        where: { id: s.batchId },
        select: { name: true, code: true, cohort: { select: { name: true, location: { select: { name: true } } } } },
      });
      lines.push(
        b
          ? `${b.cohort.location?.name ?? b.cohort.name} · ${b.name || b.code}`
          : `Batch ${s.batchId}`,
      );
    }
  }
  return lines;
}
