import type { PrismaClient } from "@prisma/client";
import { parseDeliveryLocationIds } from "./trainingScopeGuards.js";

export type ProviderLocationCountRow = {
  locationId: string | null;
  locationName: string;
  locationCode: string | null;
  activeCount: number;
  reserveCount: number;
  totalCount: number;
  cohortCount: number;
  trainingCount: number;
};

export type ProviderCohortLocationRow = {
  trainingId: string;
  trainingTitle: string;
  cohortId: string;
  cohortCode: string;
  cohortName: string;
  locationId: string | null;
  locationName: string;
  locationCode: string | null;
  activeCount: number;
  reserveCount: number;
  totalCount: number;
};

export type ProviderLocationBreakdown = {
  byLocation: ProviderLocationCountRow[];
  byCohort: ProviderCohortLocationRow[];
  totals: { activeCount: number; reserveCount: number; totalCount: number };
};

const UNASSIGNED_LABEL = "Unassigned location";

function bump(
  map: Map<string, { active: number; reserve: number }>,
  key: string,
  rosterRole: string,
) {
  const row = map.get(key) ?? { active: 0, reserve: 0 };
  if (rosterRole === "active") row.active += 1;
  else if (rosterRole === "reserve") row.reserve += 1;
  map.set(key, row);
}

export type TraineeLocationScope = {
  cohortLocationById: Map<string, bigint | null>;
  trainingDeliverySiteIdsByTrainingId: Map<string, string[]>;
};

/**
 * Cohort location wins when set. If the cohort has no location but the training
 * has exactly one delivery site, use that site. Never use training.locationId when
 * multiple delivery sites exist (ambiguous).
 */
export function resolveTraineeDeliveryLocationId(
  trainee: { cohortId: bigint | null; trainingId: bigint | null; locationId: bigint | null },
  scope: TraineeLocationScope,
): bigint | null {
  const sitesForTraining = trainee.trainingId
    ? scope.trainingDeliverySiteIdsByTrainingId.get(trainee.trainingId.toString())
    : undefined;
  const soleSite = sitesForTraining?.length === 1 ? BigInt(sitesForTraining[0]!) : null;

  if (trainee.cohortId) {
    const cohortLoc = scope.cohortLocationById.get(trainee.cohortId.toString());
    if (cohortLoc) return cohortLoc;
    return soleSite;
  }
  if (trainee.locationId) return trainee.locationId;
  return soleSite;
}

export function effectiveCohortLocationId(
  cohort: { locationId: bigint | null; trainingId: bigint },
  scope: TraineeLocationScope,
): bigint | null {
  if (cohort.locationId) return cohort.locationId;
  const sites = scope.trainingDeliverySiteIdsByTrainingId.get(cohort.trainingId.toString());
  if (sites?.length === 1) return BigInt(sites[0]!);
  return null;
}

export async function buildProviderLocationBreakdown(
  prisma: PrismaClient,
  projectId: bigint,
  trainingProviderId: bigint,
): Promise<ProviderLocationBreakdown> {
  const [trainees, cohorts, trainings, locations] = await Promise.all([
    prisma.trainee.findMany({
      where: { projectId, trainingProviderId },
      select: { cohortId: true, trainingId: true, locationId: true, rosterRole: true },
    }),
    prisma.trainingCohort.findMany({
      where: { projectId, trainingProviderId },
      select: {
        id: true,
        code: true,
        name: true,
        locationId: true,
        trainingId: true,
        training: { select: { title: true } },
      },
      orderBy: [{ trainingId: "asc" }, { id: "asc" }],
    }),
    prisma.training.findMany({
      where: { projectId, trainingProviderId },
      select: { id: true, deliveryLocationIds: true, locationId: true },
    }),
    prisma.location.findMany({
      where: { isActive: true },
      select: { id: true, name: true, code: true },
      orderBy: { name: "asc" },
    }),
  ]);

  const locationMeta = new Map(
    locations.map((l) => [l.id.toString(), { name: l.name, code: l.code }]),
  );
  const trainingDeliverySiteIdsByTrainingId = new Map<string, string[]>();
  for (const tr of trainings) {
    const ids = parseDeliveryLocationIds(tr.deliveryLocationIds);
    const effective =
      ids.length > 0 ? ids.map((id) => id.toString()) : tr.locationId ? [tr.locationId.toString()] : [];
    trainingDeliverySiteIdsByTrainingId.set(tr.id.toString(), effective);
  }

  const cohortLocationById = new Map<string, bigint | null>();
  for (const c of cohorts) {
    cohortLocationById.set(c.id.toString(), c.locationId);
  }
  const scope: TraineeLocationScope = { cohortLocationById, trainingDeliverySiteIdsByTrainingId };

  const byLocationKey = new Map<string, { active: number; reserve: number }>();
  const byCohortKey = new Map<string, { active: number; reserve: number }>();
  const cohortScopeByLocation = new Map<string, { cohortCount: number; trainingIds: Set<string> }>();

  for (const c of cohorts) {
    const locId = effectiveCohortLocationId(c, scope);
    const locKey = locId?.toString() ?? "__none__";
    const prev = cohortScopeByLocation.get(locKey) ?? { cohortCount: 0, trainingIds: new Set<string>() };
    prev.cohortCount += 1;
    prev.trainingIds.add(c.trainingId.toString());
    cohortScopeByLocation.set(locKey, prev);
  }
  const cohortScopeFinal = new Map<string, { cohortCount: number; trainingCount: number }>();
  for (const [key, v] of cohortScopeByLocation.entries()) {
    cohortScopeFinal.set(key, { cohortCount: v.cohortCount, trainingCount: v.trainingIds.size });
  }

  for (const t of trainees) {
    const locId = resolveTraineeDeliveryLocationId(t, scope);
    const locKey = locId?.toString() ?? "__none__";
    bump(byLocationKey, locKey, t.rosterRole);
    if (t.cohortId) {
      bump(byCohortKey, t.cohortId.toString(), t.rosterRole);
    }
  }

  const allLocationKeys = new Set<string>([...byLocationKey.keys(), ...cohortScopeFinal.keys()]);

  const byLocation: ProviderLocationCountRow[] = [];
  for (const key of allLocationKeys) {
    const counts = byLocationKey.get(key) ?? { active: 0, reserve: 0 };
    const scopeRow = cohortScopeFinal.get(key);
    const meta = key === "__none__" ? null : locationMeta.get(key);
    byLocation.push({
      locationId: key === "__none__" ? null : key,
      locationName: meta?.name ?? UNASSIGNED_LABEL,
      locationCode: meta?.code ?? null,
      activeCount: counts.active,
      reserveCount: counts.reserve,
      totalCount: counts.active + counts.reserve,
      cohortCount: scopeRow?.cohortCount ?? 0,
      trainingCount: scopeRow?.trainingCount ?? 0,
    });
  }
  byLocation.sort((a, b) => b.totalCount - a.totalCount || a.locationName.localeCompare(b.locationName));

  const byCohort: ProviderCohortLocationRow[] = [];
  for (const c of cohorts) {
    const counts = byCohortKey.get(c.id.toString()) ?? { active: 0, reserve: 0 };
    const locId = effectiveCohortLocationId(c, scope);
    const meta = locId ? locationMeta.get(locId.toString()) : null;
    byCohort.push({
      trainingId: c.trainingId.toString(),
      trainingTitle: c.training.title,
      cohortId: c.id.toString(),
      cohortCode: c.code,
      cohortName: c.name,
      locationId: locId ? locId.toString() : null,
      locationName: meta?.name ?? UNASSIGNED_LABEL,
      locationCode: meta?.code ?? null,
      activeCount: counts.active,
      reserveCount: counts.reserve,
      totalCount: counts.active + counts.reserve,
    });
  }

  let activeCount = 0;
  let reserveCount = 0;
  for (const row of byLocation) {
    activeCount += row.activeCount;
    reserveCount += row.reserveCount;
  }

  return {
    byLocation,
    byCohort,
    totals: { activeCount, reserveCount, totalCount: activeCount + reserveCount },
  };
}
