import {
  findFormForJobType,
  findGeneralJobType,
  isGeneralJobType
} from "./jobTypeHelpers.js";

export const PTW_RESUME_PERMIT_STORAGE_KEY = "ptw_resume_permit_id";
export const PTW_RESUME_INTENT_STORAGE_KEY = "ptw_resume_permit_intent";

export function storeResumePermitId(permitId) {
  if (permitId == null || permitId === "") return;
  sessionStorage.setItem(PTW_RESUME_PERMIT_STORAGE_KEY, String(permitId));
}

export function storeResumeIntent({ permitId, jobTypeId = null }) {
  if (permitId == null || permitId === "") return;
  storeResumePermitId(permitId);
  sessionStorage.setItem(
    PTW_RESUME_INTENT_STORAGE_KEY,
    JSON.stringify({
      permitId: String(permitId),
      jobTypeId: jobTypeId != null && String(jobTypeId).trim() !== "" ? String(jobTypeId) : null
    })
  );
}

export function readResumeIntent() {
  try {
    const raw = sessionStorage.getItem(PTW_RESUME_INTENT_STORAGE_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      if (parsed?.permitId) return parsed;
    }
  } catch {
    /* ignore */
  }
  const legacyPermitId = readStoredResumePermitId();
  if (legacyPermitId) {
    return { permitId: legacyPermitId, jobTypeId: null };
  }
  return null;
}

export function readStoredResumePermitId() {
  return sessionStorage.getItem(PTW_RESUME_PERMIT_STORAGE_KEY) || "";
}

export function clearStoredResumePermitId() {
  sessionStorage.removeItem(PTW_RESUME_PERMIT_STORAGE_KEY);
}

export function clearResumeIntent() {
  clearStoredResumePermitId();
  sessionStorage.removeItem(PTW_RESUME_INTENT_STORAGE_KEY);
}

/**
 * Build hub state for an active permit so the user can add specialized forms later.
 */
export async function loadPermitHubContext(
  permitId,
  { forms = [], jobTypes = [], getPermit, listSubmissions, listOpeningClosingMap }
) {
  const pid = Number(permitId);
  if (!Number.isFinite(pid) || pid <= 0) {
    throw new Error("Invalid permit id.");
  }

  const permit = await getPermit(pid);
  if (!permit) {
    throw new Error("Permit not found.");
  }
  if (!permit.valid_from) {
    throw new Error("Submit the general permit first before adding specialized forms.");
  }
  if (Number(permit.permit_status_id) === 3) {
    throw new Error("This permit is closed; no further forms can be added.");
  }

  const generalJobType = findGeneralJobType(jobTypes);
  const generalJobTypeId = Number(generalJobType?.job_type_id);

  const [submissionRows, mappingRows] = await Promise.all([
    listSubmissions({ permit_id: pid }),
    listOpeningClosingMap({ permit_id: pid })
  ]);

  const mapForPermit = (Array.isArray(mappingRows) ? mappingRows : []).find(
    (row) => Number(row.permit_id) === pid
  );
  const openingSubId =
    mapForPermit?.opening_sub_id ??
    (Array.isArray(mappingRows) ? mappingRows[0]?.opening_sub_id : null);

  const formById = Object.fromEntries(
    (Array.isArray(forms) ? forms : []).map((form) => [Number(form.form_id), form])
  );

  const specializedSubmissions = (Array.isArray(submissionRows) ? submissionRows : [])
    .filter((row) => Number(row.submission_id) !== Number(openingSubId))
    .map((row) => {
      const form = formById[Number(row.form_id)];
      const jobTypeId = Number(form?.job_type_id);
      if (!form || !Number.isFinite(jobTypeId) || jobTypeId <= 0) {
        return null;
      }
      if (Number.isFinite(generalJobTypeId) && jobTypeId === generalJobTypeId) {
        return null;
      }
      const jobType = (Array.isArray(jobTypes) ? jobTypes : []).find(
        (jt) => Number(jt.job_type_id) === jobTypeId
      );
      return {
        submissionId: row.submission_id,
        jobTypeName: jobType?.job_type_name || form.title || "Specialized permit"
      };
    })
    .filter(Boolean);

  return {
    permitId: String(pid),
    permitNumber: permit.permit_number || `PTW-${pid}`,
    generalSubmissionId: openingSubId != null ? Number(openingSubId) : null,
    validFrom: permit.valid_from,
    validUntil: permit.valid_until,
    specializedSubmissions
  };
}

export function buildSpecializedFormOptions(forms, jobTypes) {
  const generalJobType = findGeneralJobType(jobTypes);
  const generalId = Number(generalJobType?.job_type_id);

  return (Array.isArray(jobTypes) ? jobTypes : [])
    .filter((jt) => !isGeneralJobType(jt) && Number(jt.job_type_id) !== generalId)
    .map((jt) => {
      const form = findFormForJobType(forms, jt.job_type_id);
      return {
        jobTypeId: String(jt.job_type_id),
        jobTypeName: jt.job_type_name,
        form,
        label: form
          ? `${jt.job_type_name} — Form #${form.form_id}`
          : `${jt.job_type_name} (no form linked)`
      };
    });
}

export function resolveSpecializedForm(forms, jobTypeId) {
  return findFormForJobType(forms, jobTypeId);
}
