import type { ApplicationItem } from "@/data/mockApplications";
import { loadApplicantSubmissionRecord } from "@/lib/applicantSubmissionRecord";

/** `submissionRecord.author.id` may be a user id; case codes are usually `SUB-…` / `DRAFT-…` or not UUID-shaped. */
function looksLikeBareUuid(s: string): boolean {
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.trim());
}

/**
 * Case id for `GET /api/v1/application-drafts/:caseId` (dashboard forms).
 * Prefer server field, then the last local submission for this application, else application id.
 */
export function resolveApplicationDraftCaseId(item: ApplicationItem): string {
  const fromApi = item.draftCaseId?.trim();
  if (fromApi) return fromApi;
  const rec = loadApplicantSubmissionRecord();
  if (rec?.applicationId === item.id) {
    const fromRec = rec.caseId?.trim();
    if (fromRec) return fromRec;
  }
  // Postgres: submission id is `sub-…` but drafts live under `Initiative.case_code` (also exposed as author.id / draft_case_id).
  const aid = item.author?.id?.trim();
  const rowId = item.id.trim();
  const rowIsSubmissionKey = /^sub-/i.test(rowId);
  if (aid && rowIsSubmissionKey && aid.toLowerCase() !== rowId.toLowerCase()) {
    if (looksLikeBareUuid(aid)) {
      // Avoid using a stored user id as the draft case key; caller should refresh from GET /api/applications/:id.
      return "";
    }
    return aid;
  }
  return rowId;
}
