const API_BASE = import.meta.env.VITE_API_BASE ?? "";

async function request(path, options = {}) {
  let response;
  try {
    response = await fetch(`${API_BASE}${path}`, options);
  } catch {
    throw new Error("서버에 연결하지 못했습니다. 잠시 후 다시 시도해 주세요.");
  }

  const text = await response.text();
  let data = {};
  if (text) {
    try {
      data = JSON.parse(text);
    } catch {
      data = { detail: text.slice(0, 200) };
    }
  }

  if (!response.ok) {
    if (response.status === 413) {
      throw new Error("파일이 너무 큽니다. 업로드 제한을 확인해 주세요.");
    }
    const detail = data.detail || response.statusText || "request_failed";
    throw new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
  }
  return data;
}

export function getHealth() {
  return request("/api/health");
}

export function getJob(jobId) {
  return request(`/api/jobs/${jobId}`);
}

export function getReport(jobId) {
  return request(`/api/jobs/${jobId}/report`);
}

export function createJob(formData) {
  return request("/api/jobs", {
    method: "POST",
    body: formData,
  });
}

/** Upload zip with progress via XHR. */
export function uploadZip(file, mailbox, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    const form = new FormData();
    form.append("mailbox", mailbox);
    form.append("file", file);

    xhr.upload.onprogress = (event) => {
      if (!event.lengthComputable) return;
      const pct = Math.max(1, Math.min(99, Math.round((event.loaded / event.total) * 100)));
      onProgress?.(pct);
    };

    xhr.onload = () => {
      let data = {};
      try {
        data = JSON.parse(xhr.responseText || "{}");
      } catch {
        data = {};
      }
      if (xhr.status >= 200 && xhr.status < 300) {
        onProgress?.(100);
        resolve(data);
        return;
      }
      if (xhr.status === 413) {
        reject(new Error("파일이 너무 큽니다. 업로드 제한을 확인해 주세요."));
        return;
      }
      reject(new Error(data.detail || `upload_failed (${xhr.status})`));
    };

    xhr.onerror = () => reject(new Error("업로드 중 네트워크 오류가 발생했습니다."));
    xhr.open("POST", `${API_BASE}/api/uploads`);
    xhr.send(form);
  });
}

/** Stage a mailbox zip by uploading it to the server. */
export function stageMailboxZip(file, mailbox, onProgress) {
  return uploadZip(file, mailbox, onProgress);
}

export async function deleteUpload(uploadId) {
  if (!uploadId) return { ok: true };
  return request(`/api/uploads/${uploadId}`, { method: "DELETE" });
}
