/**
 * Admin CRUD for adjudication results (Duyệt / Từ chối) keyed by public `applicationId`.
 * Backend: `/api/applications/{applicationId}/admin-result`
 */

import { axiosSuccessStatusOnly } from "@/lib/applicationReviewApi";
import { apiClient, isApiNotFoundError } from "@/shared/api/client";

export type AdminDecision = "approved" | "rejected";

export interface AdminApplicationResultDto {
  id: string;
  applicationId: string;
  initiativeId: string;
  decision: AdminDecision;
  feedback: string;
  rationale: string | null;
  createdAt: string;
  updatedAt: string;
  createdBy: string | null;
  updatedBy: string | null;
  /** Resolved server-side from ``users.full_name`` when present */
  createdByFullName?: string | null;
  updatedByFullName?: string | null;
  applicationName: string;
}

export interface AdminApplicationResultUpsertPayload {
  decision: AdminDecision;
  feedback: string;
  rationale?: string | null;
}

function resultPath(applicationId: string): string {
  return `/api/applications/${encodeURIComponent(applicationId.trim())}/admin-result`;
}

/** READ — returns `null` when no row exists yet (404). */
export async function fetchAdminApplicationResult(
  applicationId: string,
): Promise<AdminApplicationResultDto | null> {
  const id = applicationId.trim();
  if (!id) return null;
  try {
    return await apiClient.get<AdminApplicationResultDto>(
      resultPath(id),
      axiosSuccessStatusOnly,
    );
  } catch (e) {
    if (isApiNotFoundError(e)) return null;
    throw e;
  }
}

export async function createAdminApplicationResult(
  applicationId: string,
  body: AdminApplicationResultUpsertPayload,
): Promise<AdminApplicationResultDto> {
  return apiClient.post<AdminApplicationResultDto>(
    resultPath(applicationId),
    body,
    axiosSuccessStatusOnly,
  );
}

/** Server treats PUT as create-or-replace (idempotent upsert). */
export async function updateAdminApplicationResult(
  applicationId: string,
  body: AdminApplicationResultUpsertPayload,
): Promise<AdminApplicationResultDto> {
  return apiClient.put<AdminApplicationResultDto>(
    resultPath(applicationId),
    body,
    axiosSuccessStatusOnly,
  );
}

export async function deleteAdminApplicationResult(
  applicationId: string,
): Promise<{ deleted: boolean; applicationId: string }> {
  return apiClient.delete<{ deleted: boolean; applicationId: string }>(
    resultPath(applicationId),
    axiosSuccessStatusOnly,
  );
}

/**
 * Idempotent save: server `PUT …/admin-result` creates or updates in one round trip
 * (no client-side GET-before-POST — avoids 404-as-success bugs with the default Axios client).
 */
export async function upsertAdminApplicationResult(
  applicationId: string,
  body: AdminApplicationResultUpsertPayload,
): Promise<AdminApplicationResultDto> {
  return updateAdminApplicationResult(applicationId.trim(), body);
}
