import { apiClient } from "@/shared/api/client";
import type { ApplicationItem } from "@/data/mockApplications";

function unwrap<T>(raw: unknown): T {
  if (raw && typeof raw === "object" && "data" in raw && (raw as { data: unknown }).data !== undefined) {
    return (raw as { data: T }).data;
  }
  return raw as T;
}

export type CreateApplicantApplicationResult = {
  id: string;
  application: ApplicationItem;
};

/**
 * `POST /api/applications/new` — creates a shell row and returns `draftCaseId` for form drafts.
 */
export async function createApplicantApplication(
  name?: string,
): Promise<CreateApplicantApplicationResult> {
  const raw = await apiClient.post<unknown>("/api/applications/new", {
    name: (name ?? "").trim(),
  });
  return unwrap<CreateApplicantApplicationResult>(raw);
}

/**
 * `PUT /api/applications/{id}` — update display name and submitted date (metadata only).
 */
export async function updateApplicantApplication(
  applicationId: string,
  payload: { name: string; submittedDate: string },
): Promise<ApplicationItem> {
  const raw = await apiClient.put<unknown>(`/api/applications/${encodeURIComponent(applicationId)}`, {
    name: payload.name.trim(),
    submittedDate: payload.submittedDate,
  });
  return unwrap<ApplicationItem>(raw);
}
