import apiClient from "@/lib/api/client";
import type { ApiResponse } from "@/lib/api/types";
export type ReportKind = "individual" | "team" | "organization";
export interface ReportEntry {
  id: number; title: string; type: string; date: string; end_date?: string | null;
  learning_type?: "course" | "class_workshop" | "space" | "internship" | null;
  /** Null on sponsorship and development rows — those carry `learners`. */
  beneficiaries: number | null; attendees: number | null; learners?: number | null; scheduled_hours: number | null;
  actual_hours: number | null; economic_impact: number | null;
  role?: "organizer" | "sponsor" | "volunteer" | "provider" | "participant" | null; is_paid?: boolean; certificate_url?: string | null;
  certificate_issuer?: string | null; publisher_name?: string | null;
}
export interface AccountReport {
  kind: ReportKind; year: number; available_years: number[];
  full_name: string; civil_id?: string | null; license_number?: string | null; phone?: string | null;
  /** KWD per actual hour behind `economic_impact` (PDF footer, organizations and teams). */
  economic_impact_rate_kwd?: number | null;
  stats: { actual_hours: number; volunteer_opportunities: number; development_opportunities: number;
    /** `null` on the individual report until the backend computes it (client answers p.1, items 3–4). */
    sponsorships: number | null; beneficiaries: number | null; learners: number | null; economic_impact: number | null };
  volunteer_opportunities: ReportEntry[]; development_opportunities: ReportEntry[]; sponsorships: ReportEntry[];
  generated_at: string;
}
/** Owner is derived from the token. No caller-supplied account identifier. */
export const getAccountReport = (year: number | undefined, language: "ar" | "en"): Promise<ApiResponse<AccountReport>> =>
  apiClient.get("/achievement-report/", { params: { year, language } }).then(r => r.data);
export const exportAccountReport = async (year: number, language: "ar" | "en"): Promise<Blob> => {
  const response = await apiClient.get("/achievement-report/export/", { params: { year, language }, responseType: "blob" });
  const blob = response.data as Blob;
  if (!(blob instanceof Blob) || blob.type.split(";")[0].trim().toLowerCase() !== "application/pdf" || await blob.slice(0, 5).text() !== "%PDF-") throw new Error("Invalid report PDF");
  return blob;
};
