// API layer — всі виклики до FastAPI backend

const BASE = window.location.hostname === 'localhost' ? 'http://localhost:8000' : '/api';

async function req(path, opts = {}) {
  const res = await fetch(BASE + path, {
    credentials: 'include',
    headers: { 'Content-Type': 'application/json', ...opts.headers },
    ...opts,
  });

  if (res.status === 401) {
    const err = new Error('Unauthorized');
    err.status = 401;
    throw err;
  }

  if (!res.ok) {
    const text = await res.text().catch(() => res.statusText);
    throw new Error(`${res.status}: ${text}`);
  }

  if (res.status === 204) return null;
  return res.json();
}

async function streamPost(path, body, onEvent) {
  const res = await fetch(BASE + path, {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (res.status === 401) { const err = new Error('Unauthorized'); err.status = 401; throw err; }
  if (!res.ok) throw new Error(`${res.status}: ${await res.text().catch(() => res.statusText)}`);

  const reader  = res.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split('\n');
    buffer = lines.pop();
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        try { onEvent(JSON.parse(line.slice(6))); } catch {}
      }
    }
  }
}

window.CIE_API = {
  // Auth
  getMe:   () => req('/auth/me'),
  logout:  () => req('/auth/logout', { method: 'POST' }),

  loginWithPassword: async (username, password) => {
    const res = await fetch(BASE + '/auth/login', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password }),
    });
    if (res.status === 401) {
      const err = new Error('Invalid credentials');
      err.status = 401;
      throw err;
    }
    if (!res.ok) throw new Error(await res.text().catch(() => res.statusText));
    return res.json();
  },

  // Dashboard
  getServers:    ()         => req('/servers'),

  // Config editor
  getConfig:     (id)       => req(`/configs/${id}`),
  putConfig:     (id, body) => req(`/configs/${id}`, { method: 'PUT', body: JSON.stringify(body) }),
  initConfig:    (id)       => req(`/configs/${id}/init`, { method: 'POST' }),

  // Settings — users (owner only)
  getUsers:      ()         => req('/users'),
  postUser:      (body)     => req('/users', { method: 'POST', body: JSON.stringify(body) }),
  putUser:       (u, body)  => req(`/users/${u}`, { method: 'PUT', body: JSON.stringify(body) }),
  deleteUser:    (u)        => req(`/users/${u}`, { method: 'DELETE' }),

  // Mods matrix
  getMods:       ()        => req('/mods'),
  lookupMod:     (url)     => req(`/mods/lookup?url=${encodeURIComponent(url)}`),
  syncMod:        (body)           => req('/mods/sync',    { method: 'POST', body: JSON.stringify(body) }),
  removeMod:      (body)           => req('/mods/remove',  { method: 'POST', body: JSON.stringify(body) }),
  publishMods:    (body)           => req('/mods/publish', { method: 'POST', body: JSON.stringify(body) }),

  // Audit log
  getAuditLog:       ()    => req('/audit'),
  getServerAuditLog: (sid) => req(`/audit/${sid}`),

  // Scenarios
  getScenarios:      ()          => req('/scenarios'),
  postScenario:      (body)      => req('/scenarios', { method: 'POST', body: JSON.stringify(body) }),
  putScenario:       (idx, body) => req(`/scenarios/${idx}`, { method: 'PUT', body: JSON.stringify(body) }),
  deleteScenario:    (idx)       => req(`/scenarios/${idx}`, { method: 'DELETE' }),

  // Settings — server roster (owner only)
  getServerList: ()         => req('/servers/list'),
  postServer:    (body)     => req('/servers', { method: 'POST', body: JSON.stringify(body) }),
  putServer:      (id, body) => req(`/servers/${id}`, { method: 'PUT', body: JSON.stringify(body) }),
  deleteServer:   (id)       => req(`/servers/${id}`, { method: 'DELETE' }),
  reorderServers: (order)    => req('/servers/reorder', { method: 'POST', body: JSON.stringify({ order }) }),
};
