const BASE = `${import.meta.env.BASE_URL}api/v1`.replace(/\/+$/, "");

async function request<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${url}`, {
    headers: { "Content-Type": "application/json" },
    ...options,
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(body.error?.message || `HTTP ${res.status}`);
  }
  return res.json();
}

export const api = {
  // Templates
  getTemplates: () => request<{ data: any[] }>("/templates"),
  getTemplate: (id: string) => request<{ data: any }>(`/templates/${id}`),

  // Creatives
  getCreatives: (params?: { status?: string }) => {
    const qs = params ? "?" + new URLSearchParams(params).toString() : "";
    return request<{ data: any[] }>(`/creatives${qs}`);
  },
  createCreative: (body: { name: string; templateId: string }) =>
    request<{ data: any }>("/creatives", {
      method: "POST",
      body: JSON.stringify(body),
    }),
  getCreative: (id: string) => request<{ data: any }>(`/creatives/${id}`),
  updateCreative: (id: string, body: { name?: string; theme?: Record<string, string> }) =>
    request<{ data: any }>(`/creatives/${id}`, {
      method: "PATCH",
      body: JSON.stringify(body),
    }),
  deleteCreative: (id: string) =>
    request<{ data: any }>(`/creatives/${id}`, { method: "DELETE" }),

  // Assets
  uploadAssets: (creativeId: string, file: File) => {
    const formData = new FormData();
    formData.append("file", file);
    return fetch(`${BASE}/creatives/${creativeId}/assets/upload`, {
      method: "POST",
      body: formData,
    }).then((res) => {
      if (!res.ok) return res.json().then((b) => { throw new Error(b.error?.message); });
      return res.json();
    });
  },
  importFromUrl: (creativeId: string, url: string) =>
    request<{ data: any }>(`/creatives/${creativeId}/assets/upload`, {
      method: "POST",
      body: JSON.stringify({ url }),
    }),
  clearAssets: (creativeId: string) =>
    request<{ data: any }>(`/creatives/${creativeId}/assets`, { method: "DELETE" }),

  // Preview
  startPreview: (creativeId: string, theme?: Record<string, string>) =>
    request<{ data: { url: string } }>(`/creatives/${creativeId}/preview/start`, {
      method: "POST",
      body: theme ? JSON.stringify({ theme }) : undefined,
    }),
  stopPreview: (creativeId: string) =>
    request<{ data: any }>(`/creatives/${creativeId}/preview/stop`, { method: "POST" }),

  // Builds
  triggerBuild: (creativeId: string, body: { platforms: string[]; theme: Record<string, string> }) =>
    request<{ data: any }>(`/creatives/${creativeId}/builds`, {
      method: "POST",
      body: JSON.stringify(body),
    }),
  getBuilds: (creativeId: string) =>
    request<{ data: any[] }>(`/creatives/${creativeId}/builds`),
  getBuildStatus: (buildId: string) =>
    request<{ data: any }>(`/builds/${buildId}/status`),
};
