import { env } from '@/shared/config/env';
import { getAccessToken } from '@/shared/utils/token';
import { fetchWithTimeout, isAbortError, FETCH_SUBMIT_DEADLINE_MS } from '@/lib/networkTimeout';

export interface SubmitInitiativeMetadata {
  initiativeName: string;
  authorName: string;
  authorEmail?: string;
  authorPhone?: string;
  /** Postgres `Initiative.case_code` (CASE-…) — must match application-drafts autosave. */
  initiativeCaseId?: string;
  /** Deprecated: was client `draft.draftId` (DRAFT-…); keep only for backward compatibility. */
  caseId?: string;
  topicType?: string;
}

export interface SubmitInitiativeResponse {
  id: string;
  submittedDate: string;
  publicUrl: string;
  name?: string;
}

/**
 * Upload full PDF hồ sơ (đơn + báo cáo) to the API; admin « Danh Sách Sáng kiến » reads from GET /api/applications.
 */
export async function submitInitiativePdf(
  blob: Blob,
  fileName: string,
  metadata: SubmitInitiativeMetadata,
): Promise<SubmitInitiativeResponse> {
  const fd = new FormData();
  fd.append('file', blob, fileName);
  fd.append('metadata', JSON.stringify(metadata));
  const token = getAccessToken();
  let res: Response;
  try {
    res = await fetchWithTimeout(
      `${env.API_URL}/api/applications/submit`,
      {
        method: 'POST',
        headers: token ? { Authorization: `Bearer ${token}` } : undefined,
        body: fd,
        credentials: 'include',
      },
      FETCH_SUBMIT_DEADLINE_MS,
    );
  } catch (err) {
    if (isAbortError(err)) {
      throw new Error(
        `Gửi hồ sơ quá lâu sau ${Math.round(FETCH_SUBMIT_DEADLINE_MS / 1000)} giây. Kiểm tra mạng hoặc file PDF quá lớn, rồi thử lại.`,
      );
    }
    throw err;
  }
  if (!res.ok) {
    let message = res.statusText;
    try {
      const j = (await res.json()) as { detail?: unknown };
      if (typeof j.detail === 'string') {
        message = j.detail;
      } else if (Array.isArray(j.detail)) {
        message = JSON.stringify(j.detail);
      } else if (j.detail && typeof j.detail === 'object') {
        const d = j.detail as { message?: string; missing?: string[] };
        const header = typeof d.message === 'string' ? d.message : '';
        const lines = Array.isArray(d.missing) ? d.missing.filter(Boolean).join('\n') : '';
        message = [header, lines].filter(Boolean).join('\n') || message;
      }
    } catch {
      try {
        message = await res.text();
      } catch {
        /* ignore */
      }
    }
    throw new Error(message || 'Gửi hồ sơ thất bại');
  }
  return res.json() as Promise<SubmitInitiativeResponse>;
}
