import { prisma } from "../prisma.js";
import { buildIndicatorKpiPayload } from "./indicatorKpis.js";
import { computeAttendancePresentPossible } from "./attendanceRollup.js";
import { fetchAttendanceDailySeries } from "./attendanceDailySeries.js";
import { computeRosterInsights, type RosterInsightsItem } from "./rosterInsights.js";
import { cacheGet, cacheSet } from "./simpleCache.js";
import type { ProjectScope } from "./scopePolicy.js";
import { traineeDeliveryScopeWhere, loadAllowedBatchIds, hasProviderWideAccess } from "./scopePolicy.js";

const DASHBOARD_CACHE_TTL_MS = 45_000;

function asId(v: bigint) {
  return v.toString();
}

export type DashboardProviderItem = { id: string; tpCode: string; name: string };

export type DashboardSubmissionItem = {
  id: string;
  activityCode: string;
  activityName: string;
  trainingProviderId: string;
  tpCode: string;
  tpName: string;
  status: string;
  submittedAt: string | null;
};

export type DashboardPayload = {
  cached: boolean;
  providers: { items: DashboardProviderItem[] };
  indicatorKpis: Awaited<ReturnType<typeof buildIndicatorKpiPayload>>;
  attendance: {
    project: { present: number; possible: number; ratePct: number };
    items: Array<{ tpId: string; present: number; possible: number; ratePct: number }>;
  };
  attendanceDaily: { items: Awaited<ReturnType<typeof fetchAttendanceDailySeries>> };
  submissions: { items: DashboardSubmissionItem[] };
  rosterInsights: { item: RosterInsightsItem };
};

async function loadSubmissions(projectId: bigint, scope: ProjectScope): Promise<DashboardSubmissionItem[]> {
  const items = await prisma.tpActivitySubmission.findMany({
    where: { projectId, ...(scope.providerId ? { trainingProviderId: scope.providerId } : {}) },
    orderBy: { id: "desc" },
    take: 200,
    include: {
      activity: { select: { code: true, name: true } },
      trainingProvider: { select: { id: true, tpCode: true, name: true } },
    },
  });
  return items.map((s) => ({
    id: asId(s.id),
    activityCode: s.activity.code,
    activityName: s.activity.name,
    trainingProviderId: asId(s.trainingProviderId),
    tpCode: s.trainingProvider.tpCode,
    tpName: s.trainingProvider.name,
    status: s.status,
    submittedAt: s.submittedAt?.toISOString() ?? null,
  }));
}

async function loadProviders(projectId: bigint, scope: ProjectScope): Promise<DashboardProviderItem[]> {
  const items = await prisma.trainingProvider.findMany({
    where: { projectId, ...(scope.providerId ? { id: scope.providerId } : {}) },
    select: { id: true, tpCode: true, name: true },
    orderBy: { id: "desc" },
  });
  return items.map((p) => ({ id: asId(p.id), tpCode: p.tpCode, name: p.name }));
}

function buildAttendanceSummary(
  scope: ProjectScope,
  agg: Awaited<ReturnType<typeof computeAttendancePresentPossible>>,
) {
  const items: Array<{ tpId: string; present: number; possible: number; ratePct: number }> = [];
  for (const [tpId, v] of agg.byTp) {
    if (scope.providerId && scope.providerId.toString() !== tpId) continue;
    const ratePct = v.possible > 0 ? Math.round((v.present / v.possible) * 10000) / 100 : 0;
    items.push({ tpId, present: v.present, possible: v.possible, ratePct });
  }
  const totalRate = agg.possible > 0 ? Math.round((agg.present / agg.possible) * 10000) / 100 : 0;
  return {
    project: { present: agg.present, possible: agg.possible, ratePct: totalRate },
    items,
  };
}

export async function buildDashboardPayload(opts: {
  projectId: bigint;
  userId: bigint;
  scope: ProjectScope;
  trainingProviderId?: bigint;
  dailyLimit?: number;
}): Promise<DashboardPayload> {
  const { projectId, scope, userId } = opts;
  const effectiveTpId = scope.providerId ?? opts.trainingProviderId;
  const dailyLimit = opts.dailyLimit ?? 42;
  const cacheKey = `dashboard:${projectId}:${userId}:${effectiveTpId?.toString() ?? "all"}:${dailyLimit}`;
  const cached = cacheGet<DashboardPayload>(cacheKey);
  if (cached) return { ...cached, cached: true };

  const [providers, indicatorKpis, agg, attendanceDaily, submissions, rosterItem] = await Promise.all([
    loadProviders(projectId, scope),
    buildIndicatorKpiPayload(projectId),
    computeAttendancePresentPossible(projectId),
    (async () => {
      const batchIds = await loadAllowedBatchIds(prisma, projectId, scope);
      if (!batchIds?.length && scope.role === "tp" && !hasProviderWideAccess(scope)) {
        return [] as Awaited<ReturnType<typeof fetchAttendanceDailySeries>>;
      }
      return fetchAttendanceDailySeries(projectId, dailyLimit, effectiveTpId, batchIds ?? undefined);
    })(),
    loadSubmissions(projectId, scope),
    computeRosterInsights(projectId, effectiveTpId, traineeDeliveryScopeWhere(scope)),
  ]);

  const payload: DashboardPayload = {
    cached: false,
    providers: { items: providers },
    indicatorKpis,
    attendance: buildAttendanceSummary(scope, agg),
    attendanceDaily: { items: attendanceDaily },
    submissions: { items: submissions },
    rosterInsights: { item: rosterItem },
  };
  cacheSet(cacheKey, payload, DASHBOARD_CACHE_TTL_MS);
  return payload;
}
