import { apiClient } from '@/shared/api/client';
import type { PdfTextLayoutEdit } from '@/components/applicant/initiative-draft/pdfLayoutEditor';

type StoredOfficialFormLayoutPdf = {
  storageKey: string;
  originalName?: string | null;
  byteSize?: number | null;
  uploadedAt?: string | null;
  downloadUrl?: string | null;
  viewUrl?: string | null;
};

export type OfficialFormLayoutPayload = {
  caseId: string;
  layoutEdits: PdfTextLayoutEdit[];
  updatedAt?: string | null;
  pdf?: StoredOfficialFormLayoutPdf | null;
};

export async function getOfficialFormLayout(caseId: string): Promise<OfficialFormLayoutPayload> {
  const safeCaseId = encodeURIComponent(caseId.trim() || caseId);
  return apiClient.get<OfficialFormLayoutPayload>(`/api/v1/application-drafts/${safeCaseId}/official-form-layout`);
}

export type SaveOfficialFormLayoutResponse = {
  ok: boolean;
  caseId: string;
  layoutEdits: PdfTextLayoutEdit[];
  storageKey: string;
  byteSize?: number | null;
  uploadedAt?: string | null;
};

export async function saveOfficialFormLayout(
  caseId: string,
  layoutEdits: PdfTextLayoutEdit[],
  pdfBlob: Blob,
  fileName = 'official-form-layout.pdf',
): Promise<SaveOfficialFormLayoutResponse> {
  const safeCaseId = encodeURIComponent(caseId.trim() || caseId);
  const form = new FormData();
  form.append('layout_edits_json', JSON.stringify(layoutEdits));
  form.append('file', new File([pdfBlob], fileName, { type: 'application/pdf' }));
  return apiClient.post<SaveOfficialFormLayoutResponse>(
    `/api/v1/application-drafts/${safeCaseId}/official-form-layout`,
    form,
  );
}
