import { normalizeLauncherData, type LauncherData } from "./mockApi";

export interface StoredFileResponse {
  ok: true;
  url: string;
  fileName: string;
  originalFileName: string;
  mimeType: string;
}

export async function uploadStorageFile(file: File): Promise<StoredFileResponse> {
  const dataUrl = await readFileAsDataUrl(file);
  const response = await fetch("/api/storage/upload", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      fileName: file.name,
      mimeType: file.type || "application/octet-stream",
      dataUrl,
    }),
  });

  if (!response.ok) {
    const message = await readErrorMessage(response);
    throw new Error(message || "Не удалось сохранить файл в storage");
  }

  return response.json() as Promise<StoredFileResponse>;
}

export async function loadPersistedLauncherData(): Promise<LauncherData | null> {
  try {
    const response = await fetch("/api/storage/data", { cache: "no-store" });

    if (!response.ok) return null;

    const data = normalizeLauncherData((await response.json()) as Partial<LauncherData>);

    return data.users.length > 0 ? data : null;
  } catch {
    return null;
  }
}

export async function persistLauncherData(data: LauncherData): Promise<void> {
  const response = await fetch("/api/storage/data", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });

  if (!response.ok) {
    const message = await readErrorMessage(response);
    throw new Error(message || "Не удалось сохранить состояние витрины");
  }
}

function readFileAsDataUrl(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => resolve(String(reader.result)));
    reader.addEventListener("error", () => reject(reader.error ?? new Error("Не удалось прочитать файл")));
    reader.readAsDataURL(file);
  });
}

async function readErrorMessage(response: Response) {
  try {
    const payload = (await response.json()) as { error?: string };
    return payload.error;
  } catch {
    return response.statusText;
  }
}
