export const COUNCIL_REVIEW_OUTCOMES_STORAGE_KEY = "council-evaluation-review-outcomes-v1";

export type CouncilReviewOutcomeRecord = {
  savedAt: string;
  applicationId: string;
  caseId: string;
  initiativeName: string;
  authorName: string;
  decision: "approved" | "rejected";
  recommendedRank: string;
  recommendedRankDetail: string;
  evidencePathLabel: string;
  totalScore?: number;
  feedback?: string;
};

function readAll(): CouncilReviewOutcomeRecord[] {
  try {
    const raw = localStorage.getItem(COUNCIL_REVIEW_OUTCOMES_STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw) as unknown;
    return Array.isArray(parsed) ? (parsed as CouncilReviewOutcomeRecord[]) : [];
  } catch {
    return [];
  }
}

/** Đọc nhật ký quyết định Phiếu đánh giá (localStorage). */
export function listCouncilReviewOutcomes(): CouncilReviewOutcomeRecord[] {
  return readAll();
}

/** Lưu nhật ký quyết định Hội đồng (phiên bản front-end; có thể thay bằng API sau). */
export const COUNCIL_REVIEW_OUTCOMES_CHANGED_EVENT = "council-review-outcomes-changed";

export function saveCouncilReviewOutcome(entry: Omit<CouncilReviewOutcomeRecord, "savedAt">): void {
  const row: CouncilReviewOutcomeRecord = { ...entry, savedAt: new Date().toISOString() };
  const next = [row, ...readAll()].slice(0, 500);
  localStorage.setItem(COUNCIL_REVIEW_OUTCOMES_STORAGE_KEY, JSON.stringify(next));
  if (typeof window !== "undefined") {
    window.dispatchEvent(new CustomEvent(COUNCIL_REVIEW_OUTCOMES_CHANGED_EVENT));
  }
}
