import { Prisma } from "@prisma/client";
import { prisma } from "../prisma.js";
import { cacheGet, cacheSet } from "./simpleCache.js";
import { trackedRosterRoleFilter } from "./traineeRoster.js";

export type RosterInsightsItem = {
  totalTracked: number;
  /** @deprecated Use totalTracked */
  totalActive: number;
  sex: { male: number; female: number; other: number };
  inclusion: { disability: number; idp: number; returnee: number; lowIncome: number };
};

const ROSTER_CACHE_TTL_MS = 45_000;
const TRACKED_WHERE = trackedRosterRoleFilter();

type RosterAggRow = {
  total_tracked: bigint;
  male_cnt: bigint;
  female_cnt: bigint;
  disability_cnt: bigint;
  idp_cnt: bigint;
  returnee_cnt: bigint;
  low_income_cnt: bigint;
};

function isMaleSex(sex: string | null | undefined): boolean {
  const s = (sex ?? "").trim().toLowerCase();
  return s === "m" || s === "male" || s === "man" || s.startsWith("m");
}

function isFemaleSex(sex: string | null | undefined): boolean {
  const s = (sex ?? "").trim().toLowerCase();
  return s === "f" || s === "female" || s === "woman" || s.startsWith("f");
}

function aggregateRosterRows(
  rows: Array<{
    sex: string | null;
    disabilityFlag: boolean | null;
    idpFlag: boolean | null;
    returneeFlag: boolean | null;
    lowIncomeFlag: boolean | null;
  }>,
): RosterInsightsItem {
  let male = 0;
  let female = 0;
  let disability = 0;
  let idp = 0;
  let returnee = 0;
  let lowIncome = 0;
  for (const r of rows) {
    if (isMaleSex(r.sex)) male++;
    else if (isFemaleSex(r.sex)) female++;
    if (r.disabilityFlag) disability++;
    if (r.idpFlag) idp++;
    if (r.returneeFlag) returnee++;
    if (r.lowIncomeFlag) lowIncome++;
  }
  const totalTracked = rows.length;
  return {
    totalTracked,
    totalActive: totalTracked,
    sex: { male, female, other: Math.max(0, totalTracked - male - female) },
    inclusion: { disability, idp, returnee, lowIncome },
  };
}

/** Single-pass aggregate for tracked roster (active + reserve) charts. */
export async function computeRosterInsights(
  projectId: bigint,
  trainingProviderId?: bigint,
  deliveryScopeWhere?: Prisma.TraineeWhereInput,
): Promise<RosterInsightsItem> {
  const scopeKey = deliveryScopeWhere ? "scoped" : "all";
  const cacheKey = `roster:${projectId}:${trainingProviderId?.toString() ?? "all"}:${scopeKey}:tracked`;
  const cached = cacheGet<RosterInsightsItem>(cacheKey);
  if (cached) return cached;

  if (deliveryScopeWhere) {
    const rows = await prisma.trainee.findMany({
      where: {
        projectId,
        rosterRole: TRACKED_WHERE,
        ...(trainingProviderId ? { trainingProviderId } : {}),
        ...deliveryScopeWhere,
      },
      select: {
        sex: true,
        disabilityFlag: true,
        idpFlag: true,
        returneeFlag: true,
        lowIncomeFlag: true,
      },
    });
    const item = aggregateRosterRows(rows);
    cacheSet(cacheKey, item, ROSTER_CACHE_TTL_MS);
    return item;
  }

  const rows = trainingProviderId
    ? await prisma.$queryRaw<RosterAggRow[]>(Prisma.sql`
        SELECT
          COUNT(*) AS total_tracked,
          SUM(CASE
            WHEN LOWER(TRIM(COALESCE(sex, ''))) IN ('m', 'male', 'man')
              OR LOWER(TRIM(COALESCE(sex, ''))) LIKE 'm%' THEN 1
            ELSE 0
          END) AS male_cnt,
          SUM(CASE
            WHEN NOT (
              LOWER(TRIM(COALESCE(sex, ''))) IN ('m', 'male', 'man')
              OR LOWER(TRIM(COALESCE(sex, ''))) LIKE 'm%'
            ) AND (
              LOWER(TRIM(COALESCE(sex, ''))) IN ('f', 'female', 'woman')
              OR LOWER(TRIM(COALESCE(sex, ''))) LIKE 'f%'
            ) THEN 1
            ELSE 0
          END) AS female_cnt,
          SUM(CASE WHEN disability_flag = 1 THEN 1 ELSE 0 END) AS disability_cnt,
          SUM(CASE WHEN idp_flag = 1 THEN 1 ELSE 0 END) AS idp_cnt,
          SUM(CASE WHEN returnee_flag = 1 THEN 1 ELSE 0 END) AS returnee_cnt,
          SUM(CASE WHEN low_income_flag = 1 THEN 1 ELSE 0 END) AS low_income_cnt
        FROM trainees
        WHERE project_id = ${projectId}
          AND roster_role IN ('active', 'reserve')
          AND training_provider_id = ${trainingProviderId}
      `)
    : await prisma.$queryRaw<RosterAggRow[]>(Prisma.sql`
        SELECT
          COUNT(*) AS total_tracked,
          SUM(CASE
            WHEN LOWER(TRIM(COALESCE(sex, ''))) IN ('m', 'male', 'man')
              OR LOWER(TRIM(COALESCE(sex, ''))) LIKE 'm%' THEN 1
            ELSE 0
          END) AS male_cnt,
          SUM(CASE
            WHEN NOT (
              LOWER(TRIM(COALESCE(sex, ''))) IN ('m', 'male', 'man')
              OR LOWER(TRIM(COALESCE(sex, ''))) LIKE 'm%'
            ) AND (
              LOWER(TRIM(COALESCE(sex, ''))) IN ('f', 'female', 'woman')
              OR LOWER(TRIM(COALESCE(sex, ''))) LIKE 'f%'
            ) THEN 1
            ELSE 0
          END) AS female_cnt,
          SUM(CASE WHEN disability_flag = 1 THEN 1 ELSE 0 END) AS disability_cnt,
          SUM(CASE WHEN idp_flag = 1 THEN 1 ELSE 0 END) AS idp_cnt,
          SUM(CASE WHEN returnee_flag = 1 THEN 1 ELSE 0 END) AS returnee_cnt,
          SUM(CASE WHEN low_income_flag = 1 THEN 1 ELSE 0 END) AS low_income_cnt
        FROM trainees
        WHERE project_id = ${projectId}
          AND roster_role IN ('active', 'reserve')
      `);

  const row = rows[0];
  const totalTracked = Number(row?.total_tracked ?? 0);
  const male = Number(row?.male_cnt ?? 0);
  const female = Number(row?.female_cnt ?? 0);
  const item: RosterInsightsItem = {
    totalTracked,
    totalActive: totalTracked,
    sex: { male, female, other: Math.max(0, totalTracked - male - female) },
    inclusion: {
      disability: Number(row?.disability_cnt ?? 0),
      idp: Number(row?.idp_cnt ?? 0),
      returnee: Number(row?.returnee_cnt ?? 0),
      lowIncome: Number(row?.low_income_cnt ?? 0),
    },
  };
  cacheSet(cacheKey, item, ROSTER_CACHE_TTL_MS);
  return item;
}
