import { supabase } from './supabase.js';

// Ruft die CMS-API (gleiche Origin) mit dem aktuellen Supabase-Token auf.
async function call(path, options = {}) {
  const { data } = await supabase.auth.getSession();
  const token = data?.session?.access_token;
  const res = await fetch(`/api${path}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...options.headers,
    },
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
  return json;
}

// Datei-Upload (multipart): Browser setzt den Header selbst.
async function uploadFile(file) {
  const { data } = await supabase.auth.getSession();
  const token = data?.session?.access_token;
  const form = new FormData();
  form.append('file', file);
  const res = await fetch('/api/upload', {
    method: 'POST',
    headers: token ? { Authorization: `Bearer ${token}` } : {},
    body: form,
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
  return json;
}

export const api = {
  list: () => call('/content'),
  read: (path) => call(`/content/entry?path=${encodeURIComponent(path)}`),
  save: (path, frontmatter, body) =>
    call('/content/entry', { method: 'PUT', body: JSON.stringify({ path, frontmatter, body }) }),
  preview: (path) => call('/preview', { method: 'POST', body: JSON.stringify({ path }) }),
  publish: (path) => call('/publish', { method: 'POST', body: JSON.stringify({ path }) }),
  upload: uploadFile,
  getProfile: () => call('/profile'),
  saveProfile: (p) => call('/profile', { method: 'PUT', body: JSON.stringify(p) }),
  getMe: () => call('/me'),
  stats: () => call('/stats'),
  system: () => call('/system'),
  systemUpdate: () => call('/system/update'),
  schema: () => call('/schema'),
  changePassword: (current, next) => call('/account/password', { method: 'POST', body: JSON.stringify({ current, next }) }),
  listUsers: () => call('/users'),
  createUser: (email, password, role) => call('/users', { method: 'POST', body: JSON.stringify({ email, password, role }) }),
  setPassword: (id, password) => call(`/users/${id}`, { method: 'PUT', body: JSON.stringify({ password }) }),
  setRole: (id, role) => call(`/users/${id}`, { method: 'PUT', body: JSON.stringify({ role }) }),
  deleteUser: (id) => call(`/users/${id}`, { method: 'DELETE' }),

  // Foren-Verwaltung (Admin)
  listForumsAdmin: () => call('/admin/forums'),
  createForum: (f) => call('/admin/forums', { method: 'POST', body: JSON.stringify(f) }),
  updateForum: (id, f) => call(`/admin/forums/${id}`, { method: 'PUT', body: JSON.stringify(f) }),
  deleteForum: (id) => call(`/admin/forums/${id}`, { method: 'DELETE' }),

  // Moderation (Admin + Redakteur)
  modOverview: () => call('/mod/overview'),
  lockThread: (key, locked) => call('/mod/thread-lock', { method: 'POST', body: JSON.stringify({ key, locked }) }),
  deleteThread: (key) => call('/mod/thread-delete', { method: 'POST', body: JSON.stringify({ key }) }),
  deleteComment: (id) => call(`/comments/${id}`, { method: 'DELETE' }),
};
