import api, { fileUrl } from "./api.js";
import { unwrapData, unwrapList } from "./http.js";

export async function listPermits(query = {}) {
  const res = await api.get("/ptw_permits", { params: query });
  return unwrapList(res);
}

export async function createPermit(payload) {
  const res = await api.post("/ptw_permits", payload);
  return unwrapData(res);
}

export async function getPermit(permitId) {
  const res = await api.get(`/ptw_permits/${permitId}`);
  return unwrapData(res);
}

export async function updatePermit(permitId, payload) {
  const res = await api.put(`/ptw_permits/${permitId}`, payload);
  return unwrapData(res);
}

export async function deletePermit(permitId) {
  const res = await api.delete(`/ptw_permits/${permitId}`);
  return unwrapData(res);
}

function appendSubmissionFormData(fd, payload) {
  Object.entries(payload || {}).forEach(([k, v]) => {
    if (v == null) return;
    if (k === "answers" || k === "risk_orac_declaration") {
      fd.append(k, JSON.stringify(v));
    } else if (typeof v === "boolean") {
      fd.append(k, v ? "1" : "0");
    } else {
      fd.append(k, v);
    }
  });
}

function appendUploadFile(fd, fieldName, file, fallbackName = "upload.bin") {
  if (!file) return;
  if (typeof File !== "undefined" && file instanceof File) {
    fd.append(fieldName, file);
    return;
  }
  if (typeof Blob !== "undefined" && file instanceof Blob) {
    fd.append(fieldName, file, file.name || fallbackName);
  }
}

function appendMediaToFormData(fd, mediaMap = {}, sectionMedia = {}) {
  Object.entries(mediaMap || {}).forEach(([questionId, files]) => {
    (files || [])
      .filter(Boolean)
      .forEach((f) => appendUploadFile(fd, `media_${questionId}`, f));
  });
  Object.entries(sectionMedia || {}).forEach(([sectionId, kinds]) => {
    if (kinds?.video) {
      kinds.video.forEach((f) => appendUploadFile(fd, `media_section_${sectionId}_video`, f, "section-video.mp4"));
    }
    if (kinds?.signature) {
      kinds.signature.forEach((f) =>
        appendUploadFile(fd, `media_section_${sectionId}_signature`, f, "signature.png")
      );
    }
    if (kinds?.selfie) {
      kinds.selfie.forEach((f) =>
        appendUploadFile(fd, `media_section_${sectionId}_selfie`, f, "selfie.jpg")
      );
    }
  });
}

/** Save answers for a single form section (step-by-step permit workflow). */
export async function submitFormSection(payload, mediaMap = {}, sectionMedia = {}) {
  const fd = new FormData();
  appendSubmissionFormData(fd, payload);
  appendMediaToFormData(fd, mediaMap, sectionMedia);
  // Let axios set Content-Type with the multipart boundary (manual header breaks multer).
  const res = await api.post("/submissions/section", fd);
  const body = res?.data;
  return body?.data ?? body;
}

export async function createSubmission(payload, mediaMap = {}, sectionMedia = {}) {
  const fd = new FormData();
  appendSubmissionFormData(fd, payload);
  appendMediaToFormData(fd, mediaMap, sectionMedia);
  const res = await api.post("/submissions", fd);
  const body = res?.data;
  return body?.data ?? body;
}

/** Answers persisted in ptw_answers / ptw_answers_media for a submission. */
export async function getSubmissionAnswers(submissionId) {
  const res = await api.get(`/submissions/${submissionId}/answers`);
  return res?.data ?? null;
}

export async function listSubmissions(query = {}) {
  const res = await api.get("/ptw_submissions", { params: query });
  return unwrapList(res);
}

export async function listOpeningClosingMap(query = {}) {
  const res = await api.get("/ptw_opening_closing_map", { params: query });
  return unwrapList(res);
}

export async function listAnswers(query = {}) {
  const res = await api.get("/ptw_answers", { params: query });
  return unwrapList(res);
}

export async function listAnswersMedia(query = {}) {
  const res = await api.get("/ptw_answers_media", { params: query });
  return unwrapList(res);
}

export function answerMediaUrl(answersId, occurrence) {
  return fileUrl(`/ptw_answers_media/${answersId}/${occurrence}/file`);
}
