import type { AccountReport, ReportEntry, ReportKind } from "./services/accountReport";

/** Stable API type is preferred; localized labels support the initial contract. */
export function reportEntryGrantsCertificate(row: Pick<ReportEntry, "type" | "learning_type">): boolean {
  const type = (row.learning_type ?? row.type).trim().toLowerCase();
  return ["course", "internship", "دورة", "تدريب عملي"].includes(type);
}

export function canShowReportCertificate(row: ReportEntry, kind: ReportKind): boolean {
  return reportEntryGrantsCertificate(row) && !(kind === "individual" && row.role === "provider");
}

/** Learners on development and sponsorship rows; `attendees` is null on sponsorships. */
export function reportEntryLearners(row: Pick<ReportEntry, "learners" | "attendees">): number | null {
  return row.learners ?? row.attendees ?? null;
}

/** PDF pp.48-50: «ساعات التطوع» on the individual report, «إجمالي الساعات» otherwise. */
export function reportHoursColumnKey(kind: ReportKind): string {
  return kind === "individual" ? "VOLUNTEER_HOURS" : "REPORT_COL_TOTAL_HOURS";
}

export type ReportSection = "volunteer" | "development" | "sponsorship";

/**
 * The column headers of a report table, in order (PDF p.47):
 *  - volunteering: «الفرصة»، النوع، (الجهة المنظمة للفرد)، then the individual's
 *    «ساعات التطوع» or the publisher's مستفيد، مدة الفرصة، متطوع، إجمالي الساعات،
 *    الأثر الاقتصادي؛
 *  - development: «الدورة أو التدريب»، النوع، الدور أو متعلم، الشهادة، الأتعاب
 *    (individual and organization; a team's table has none)؛
 *  - sponsorships: المبادرة، الجهة المنفذة، نوع المبادرة، مستفيد، متعلم؛
 * and the date last on every table.
 */
export function reportTableColumns(kind: ReportKind, section: ReportSection): string[] {
  const individual = kind === "individual";
  if (section === "sponsorship") {
    return ["REPORT_COL_INITIATIVE", "REPORT_COL_EXECUTOR", "REPORT_COL_INITIATIVE_TYPE", "REPORT_BENEFICIARIES", "REPORT_LEARNERS", "DATE"];
  }
  if (section === "volunteer") {
    return individual
      ? ["REPORT_COL_TITLE", "REPORT_COL_ROLE", "TYPE", "REPORT_COL_PUBLISHER", reportHoursColumnKey(kind), "DATE"]
      : ["REPORT_COL_TITLE", "REPORT_COL_ROLE", "TYPE", "REPORT_BENEFICIARIES", "REPORT_COL_ATTENDEES", reportHoursColumnKey(kind), "REPORT_ECONOMIC_IMPACT", "DATE"];
  }
  return ["REPORT_COL_COURSE", "REPORT_COL_ROLE", "TYPE", ...(!individual ? ["REPORT_LEARNERS"] : []), "DATE"];
}

/**
 * A row key unique within one table. The sponsorship table mixes volunteering
 * and development rows, whose ids come from two independent sequences, so the
 * id alone can repeat; only development rows carry `learning_type`.
 */
export function reportRowKey(row: Pick<ReportEntry, "id"> & { learning_type?: unknown }): string {
  return `${"learning_type" in row ? "development" : "volunteer"}-${row.id}`;
}

/**
 * Footer notes in order (PDF pp.48-50). The economic-rate line and the
 * beneficiary/learner definitions belong to organization and team reports;
 * the official-record line to the individual one. An individual report also
 * gets the rate line once it carries an economic-impact value (client answers
 * p.1, item 3).
 */
export function reportFooterNoteKeys(
  kind: ReportKind,
  rate: number | null | undefined,
  individualEconomicImpact?: number | null
): string[] {
  const hasRate = rate != null && Number.isFinite(Number(rate));
  if (kind === "individual") {
    const showsImpact = hasRate && individualEconomicImpact != null && Number.isFinite(Number(individualEconomicImpact));
    return [...(showsImpact ? ["REPORT_ECONOMIC_RATE_NOTE"] : []), "REPORT_ACTUAL_HOURS_NOTE", "REPORT_OFFICIAL_RECORD_NOTE"];
  }
  return [...(hasRate ? ["REPORT_ECONOMIC_RATE_NOTE"] : []), "REPORT_ACTUAL_HOURS_NOTE", "REPORT_BENEFICIARIES_NOTE"];
}

/**
 * The counter cards, in order. Individual report (client answers p.1, items 3
 * and 4): volunteering hours, volunteering opportunities, development
 * opportunities and economic impact — no «متعلم». The economic impact is
 * shown only when the API sends a number: the hour value is a dashboard
 * setting, so it is never computed here.
 */
export function reportCounterKeys(
  kind: ReportKind,
  stats: Partial<AccountReport["stats"]> | null | undefined
): Array<[keyof AccountReport["stats"], string]> {
  // Match the achievements counters first, then append report-only counters.
  const keys: Array<[keyof AccountReport["stats"], string]> = [["volunteer_opportunities", "VOLUNTEER_OPPORTUNITIES"], ["development_opportunities", "REPORT_DEVELOPMENT"]];
  if (kind !== "individual") keys.push(["beneficiaries", "REPORT_BENEFICIARIES"], ["learners", "REPORT_LEARNERS"]);
  keys.push(["actual_hours", "VOLUNTEER_HOURS"]);

  const impact = stats?.economic_impact;
  if (kind !== "individual" || (impact != null && Number.isFinite(Number(impact)))) keys.push(["economic_impact", "REPORT_ECONOMIC_IMPACT"]);
  return keys;
}

/** Stable backend role codes; missing or unknown roles are never guessed. */
export function reportRoleLabelKey(role: ReportEntry["role"]): string | null {
  switch (role) {
    case "organizer": return "REPORT_ROLE_ORGANIZER";
    case "sponsor": return "REPORT_ROLE_SPONSOR";
    case "volunteer": return "REPORT_ROLE_VOLUNTEER";
    case "provider": return "PROFILE_BADGE_PROVIDER";
    case "participant": return "PROFILE_BADGE_PARTICIPANT";
    default: return null;
  }
}
