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

export type DeliveryScope =
  | { level: "provider" }
  | { level: "cohort"; trainingId: bigint; cohortId: bigint }
  | { level: "batch"; trainingId: bigint; cohortId: bigint; batchId: bigint };

export type ProjectScope = {
  role: string | null;
  providerId: bigint | null;
  staffRole?: string | null;
  deliveryScopes?: DeliveryScope[];
  isTpOrgAdmin?: boolean;
};

function forbidden(message: string): Error {
  const err = new Error(message);
  (err as Error & { status?: number }).status = 403;
  return err;
}

export async function hasProjectAccess(prisma: PrismaClient, projectId: bigint, userId: bigint): Promise<boolean> {
  const row = await prisma.projectUser.findFirst({
    where: { projectId, userId },
    select: { projectRole: true },
  });
  if (!row) return false;
  if (row.projectRole !== "tp") return true;

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

  const staff = await prisma.tpStaffMembership.findFirst({
    where: { projectId, userId, isActive: true },
    select: { id: true },
  });
  return Boolean(staff);
}

function mapDeliveryScopes(
  rows: Array<{
    scopeLevel: string;
    trainingId: bigint | null;
    cohortId: bigint | null;
    batchId: bigint | null;
  }>,
): DeliveryScope[] {
  const out: DeliveryScope[] = [];
  for (const r of rows) {
    if (r.scopeLevel === "provider") {
      out.push({ level: "provider" });
      continue;
    }
    if (r.scopeLevel === "cohort" && r.trainingId && r.cohortId) {
      out.push({ level: "cohort", trainingId: r.trainingId, cohortId: r.cohortId });
      continue;
    }
    if (r.scopeLevel === "batch" && r.trainingId && r.cohortId && r.batchId) {
      out.push({ level: "batch", trainingId: r.trainingId, cohortId: r.cohortId, batchId: r.batchId });
    }
  }
  return out;
}

export async function resolveProjectScope(prisma: PrismaClient, projectId: bigint, userId: bigint): Promise<ProjectScope> {
  const row = await prisma.projectUser.findFirst({
    where: { projectId, userId },
    select: { projectRole: true },
  });
  const role = row?.projectRole ?? null;
  if (role !== "tp") return { role, providerId: null };

  const tpOwner = await prisma.trainingProvider.findFirst({
    where: { projectId, userId },
    select: { id: true },
  });
  if (tpOwner) {
    return {
      role,
      providerId: tpOwner.id,
      staffRole: "tp_org_admin",
      isTpOrgAdmin: true,
      deliveryScopes: [{ level: "provider" }],
    };
  }

  const staff = await prisma.tpStaffMembership.findFirst({
    where: { projectId, userId, isActive: true },
    include: { deliveryScopes: true },
    orderBy: { id: "asc" },
  });
  if (!staff) return { role, providerId: null, deliveryScopes: [] };

  const deliveryScopes = mapDeliveryScopes(staff.deliveryScopes);
  const isTpOrgAdmin = staff.staffRole === "tp_org_admin" && deliveryScopes.some((s) => s.level === "provider");

  return {
    role,
    providerId: staff.trainingProviderId,
    staffRole: staff.staffRole,
    deliveryScopes,
    isTpOrgAdmin,
  };
}

export function assertTpAssigned(scope: ProjectScope) {
  if (scope.role === "tp" && !scope.providerId) {
    throw forbidden("No TP provider assignment found for current user.");
  }
}

export function enforceProviderScope(scope: ProjectScope, requestedProviderId: bigint) {
  if (scope.providerId && scope.providerId !== requestedProviderId) {
    throw forbidden("TP users can only access their own provider scope.");
  }
}

export function hasProviderWideAccess(scope: ProjectScope): boolean {
  if (scope.role !== "tp" || !scope.providerId) return true;
  if (scope.isTpOrgAdmin) return true;
  return (scope.deliveryScopes ?? []).some((s) => s.level === "provider");
}

export function isDeliveryScopeAllowed(
  scope: ProjectScope,
  args: { trainingId?: bigint | null; cohortId?: bigint | null; batchId?: bigint | null },
): boolean {
  if (scope.role !== "tp" || !scope.providerId) return true;
  if (hasProviderWideAccess(scope)) return true;
  const scopes = scope.deliveryScopes ?? [];
  if (!scopes.length) return false;

  const { trainingId, cohortId, batchId } = args;
  if (batchId != null) {
    return scopes.some(
      (s) =>
        (s.level === "batch" && s.batchId === batchId) ||
        (s.level === "cohort" && cohortId != null && s.cohortId === cohortId),
    );
  }
  if (cohortId != null) {
    return scopes.some(
      (s) =>
        (s.level === "cohort" && s.cohortId === cohortId) ||
        (s.level === "batch" && s.cohortId === cohortId),
    );
  }
  if (trainingId != null) {
    return scopes.some((s) => s.level !== "provider" && s.trainingId === trainingId);
  }
  return false;
}

export function assertDeliveryScope(
  scope: ProjectScope,
  args: { trainingId?: bigint | null; cohortId?: bigint | null; batchId?: bigint | null },
) {
  if (!isDeliveryScopeAllowed(scope, args)) {
    throw forbidden("This delivery scope is outside your assigned access.");
  }
}

export function traineeDeliveryScopeWhere(scope: ProjectScope): Prisma.TraineeWhereInput | undefined {
  if (scope.role !== "tp" || !scope.providerId || hasProviderWideAccess(scope)) return undefined;
  const scopes = scope.deliveryScopes ?? [];
  if (!scopes.length) return { id: BigInt(-1) };

  const or: Prisma.TraineeWhereInput[] = [];
  for (const s of scopes) {
    if (s.level === "provider") {
      or.push({ trainingProviderId: scope.providerId });
    } else if (s.level === "cohort") {
      or.push({ cohortId: s.cohortId });
    } else if (s.level === "batch") {
      or.push({ batchId: s.batchId });
    }
  }
  if (!or.length) return { id: BigInt(-1) };
  return { OR: or };
}

export function trainingIdsInScope(scope: ProjectScope): bigint[] | null {
  if (scope.role !== "tp" || hasProviderWideAccess(scope)) return null;
  const ids = new Set<string>();
  for (const s of scope.deliveryScopes ?? []) {
    if (s.level !== "provider") ids.add(s.trainingId.toString());
  }
  return [...ids].map((id) => BigInt(id));
}

export function filterTrainingsForScope<T extends { id: bigint }>(scope: ProjectScope, trainings: T[]): T[] {
  const allowed = trainingIdsInScope(scope);
  if (!allowed) return trainings;
  const set = new Set(allowed.map((id) => id.toString()));
  return trainings.filter((t) => set.has(t.id.toString()));
}

export function filterCohortsForScope<T extends { id: bigint; trainingId: bigint }>(
  scope: ProjectScope,
  cohorts: T[],
): T[] {
  if (scope.role !== "tp" || hasProviderWideAccess(scope)) return cohorts;
  const scopes = scope.deliveryScopes ?? [];
  const allowedCohortIds = new Set(
    scopes.filter((s) => s.level === "cohort" || s.level === "batch").map((s) => s.cohortId.toString()),
  );
  if (!allowedCohortIds.size) return [];
  return cohorts.filter((c) => allowedCohortIds.has(c.id.toString()));
}

export function filterBatchesForScope<T extends { id: bigint; cohortId: bigint; trainingId: bigint }>(
  scope: ProjectScope,
  batches: T[],
): T[] {
  if (scope.role !== "tp" || hasProviderWideAccess(scope)) return batches;
  const scopes = scope.deliveryScopes ?? [];
  const allowed = new Set<string>();
  for (const s of scopes) {
    if (s.level === "cohort") {
      for (const b of batches) {
        if (b.cohortId === s.cohortId) allowed.add(b.id.toString());
      }
    } else if (s.level === "batch") {
      allowed.add(s.batchId.toString());
    }
  }
  if (!allowed.size) return [];
  return batches.filter((b) => allowed.has(b.id.toString()));
}

export function serializeDeliveryScopes(scopes: DeliveryScope[] | undefined) {
  return (scopes ?? []).map((s) => {
    if (s.level === "provider") return { level: "provider" as const };
    if (s.level === "cohort") {
      return { level: "cohort" as const, trainingId: s.trainingId.toString(), cohortId: s.cohortId.toString() };
    }
    return {
      level: "batch" as const,
      trainingId: s.trainingId.toString(),
      cohortId: s.cohortId.toString(),
      batchId: s.batchId.toString(),
    };
  });
}

/** Batch IDs the scoped TP user may access; null = no batch filter (provider-wide or non-TP). */
export async function loadAllowedBatchIds(
  db: PrismaClient,
  projectId: bigint,
  scope: ProjectScope,
): Promise<bigint[] | null> {
  if (scope.role !== "tp" || !scope.providerId || hasProviderWideAccess(scope)) return null;
  const scopes = scope.deliveryScopes ?? [];
  if (!scopes.length) return [];
  const batchIds = new Set<string>();
  for (const s of scopes) {
    if (s.level === "batch") {
      batchIds.add(s.batchId.toString());
    } else if (s.level === "cohort") {
      const batches = await db.trainingBatch.findMany({
        where: { projectId, cohortId: s.cohortId },
        select: { id: true },
      });
      for (const b of batches) batchIds.add(b.id.toString());
    }
  }
  return [...batchIds].map((id) => BigInt(id));
}
