// Scenes API helper for Canvas Editor
import { safeJson as fetchSafeJson, stdHeaders } from './fetch-utils.js';

const NS = '/wp-json/castconductor/v5';
const EDITOR_NS = `${NS}/canvas-editor`;

export async function listScenes() {
  try {
    let res = await fetch(`${EDITOR_NS}/scenes`, { credentials: 'same-origin', headers: stdHeaders() });
    if (!res.ok) {
      console.warn('[ScenesAPI] listScenes canvas-editor namespace returned', res.status);
      // Fallback to primary namespace
      res = await fetch(`${NS}/scenes`, { credentials: 'same-origin', headers: stdHeaders() });
    }
    return fetchSafeJson(res);
  } catch (e) {
    console.warn('[ScenesAPI] listScenes failed', e);
    return { success: false, data: [] };
  }
}

export async function getActiveScene() {
  try {
    let res = await fetch(`${EDITOR_NS}/scenes/active`, { credentials: 'same-origin', headers: stdHeaders() });
    if (!res.ok) {
      console.warn('[ScenesAPI] getActiveScene canvas-editor namespace returned', res.status);
      // Fallback attempt: fetch full list and infer active flag
      const list = await listScenes();
      if (list && Array.isArray(list.data)) {
        const active = list.data.find(s => s.is_active);
        return { success: true, data: active || null };
      }
      // Direct fallback endpoint if exists
      res = await fetch(`${NS}/scenes/active`, { credentials: 'same-origin', headers: stdHeaders() });
    }
    return fetchSafeJson(res);
  } catch (e) {
    console.warn('[ScenesAPI] getActiveScene failed', e);
    return { success: false, data: null };
  }
}

export async function getScene(id) {
  if (!id) throw new Error('getScene: id required');
  const res = await fetch(`${NS}/scenes/${encodeURIComponent(id)}`, { method: 'GET', headers: stdHeaders(), credentials: 'same-origin' });
  return fetchSafeJson(res);
}

export async function activateScene(id) {
  const res = await fetch(`${NS}/scenes/${id}/activate`, { method: 'POST', headers: stdHeaders(), credentials: 'same-origin' });
  return res.ok;
}

export async function createScene(payload) {
  console.log('[ScenesAPI] createScene called with payload:', payload);
  try {
    const res = await fetch(`${NS}/scenes`, {
      method: 'POST',
      headers: stdHeaders(),
      credentials: 'same-origin',
      body: JSON.stringify(payload || { name: 'Default Scene', description: 'Auto-created', rotation_enabled: false, rotation_interval: 60, branding: {}, background: {}, metadata: {} })
    });
    console.log('[ScenesAPI] createScene response status:', res.status, res.statusText);
    const result = await fetchSafeJson(res);
    console.log('[ScenesAPI] createScene result:', result);
    return result;
  } catch (e) {
    console.error('[ScenesAPI] createScene failed:', e);
    return { success: false, error: e.message };
  }
}

export async function updateScene(id, payload) {
  const res = await fetch(`${NS}/scenes/${id}`, {
    method: 'PUT',
    headers: stdHeaders(),
    credentials: 'same-origin',
    body: JSON.stringify(payload || {})
  });
  return fetchSafeJson(res);
}

export async function putSceneContainers(id, containersPayload) {
  const res = await fetch(`${NS}/scenes/${id}/containers`, {
    method: 'PUT',
    headers: stdHeaders(),
    credentials: 'same-origin',
    body: JSON.stringify({ containers: containersPayload || [] })
  });
  return fetchSafeJson(res);
}

export async function getSceneContainers(id) {
  if (!id) throw new Error('getSceneContainers: id required');
  const res = await fetch(`${NS}/scenes/${encodeURIComponent(id)}/containers`, {
    method: 'GET',
    headers: stdHeaders(),
    credentials: 'same-origin'
  });
  return fetchSafeJson(res);
}
