import { apiRequest } from "./client";
import { arr } from "../utils/normalizers";

export type EvaluationRecordType =
  | "AWARD"
  | "PROPOSAL"
  | "SERVICE"
  | "EDUCATION"
  | "QUALIFICATION"
  | "POSITION"
  | "DUTY";

export type EvaluationSubmissionRecord = {
  type: EvaluationRecordType;
  source: string;
  row: any;
};

const recordEndpoints: Record<EvaluationRecordType, string> = {
  AWARD: "/api/evaluation/awards",
  PROPOSAL: "/api/evaluation/proposals",
  SERVICE: "/api/evaluation/service-impacts",
  EDUCATION: "/api/evaluation/education-records",
  QUALIFICATION: "/api/evaluation/qualifications",
  POSITION: "/api/evaluation/social-positions",
  DUTY: "/api/evaluation/duty-records"
};

export function getMyEvaluation() {
  return apiRequest("/api/evaluation/me");
}

export function getEvaluationGuide() {
  return apiRequest("/api/evaluation/configs/guide");
}

export function getEvaluationRecords(type: EvaluationRecordType) {
  return apiRequest(`${recordEndpoints[type]}/mine`).then((data) => arr(data));
}

export function submitEvaluationRecord(type: EvaluationRecordType, data: any) {
  return apiRequest(recordEndpoints[type], {
    method: "POST",
    data
  });
}

export function updateEvaluationRecord(type: EvaluationRecordType, id: number | string, data: any) {
  return apiRequest(`${recordEndpoints[type]}/${encodeURIComponent(String(id))}`, {
    method: "PUT",
    data
  });
}

export async function getAllEvaluationRecords(): Promise<EvaluationSubmissionRecord[]> {
  const entries = Object.entries(recordEndpoints) as Array<[EvaluationRecordType, string]>;
  const results = await Promise.allSettled(entries.map(([type]) => getEvaluationRecords(type)));
  return results.flatMap((result, index) => {
    if (result.status !== "fulfilled" || !Array.isArray(result.value)) return [];
    const [type, source] = entries[index];
    return result.value.map((row) => ({ type, source, row }));
  });
}
