export const prerender = false;

import type { APIRoute } from 'astro';
import { loadContent, saveContent } from '../../../lib/content';
import { CONTENT_SCHEMAS, type ContentKey } from '../../../content/schemas';

function isValidSection(s: string): s is ContentKey {
  return s in CONTENT_SCHEMAS;
}

export const GET: APIRoute = async ({ params }) => {
  const section = params.section ?? '';
  if (!isValidSection(section)) {
    return new Response(JSON.stringify({ error: 'unknown_section' }), { status: 404 });
  }
  try {
    const data = await loadContent(section);
    return new Response(JSON.stringify(data), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (err) {
    console.error('[content] load_failed', section, err);
    return new Response(JSON.stringify({ error: 'load_failed' }), { status: 500 });
  }
};

export const PUT: APIRoute = async ({ params, request }) => {
  const section = params.section ?? '';
  if (!isValidSection(section)) {
    return new Response(JSON.stringify({ error: 'unknown_section' }), { status: 404 });
  }
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return new Response(JSON.stringify({ error: 'invalid_body' }), { status: 400 });
  }
  try {
    const saved = await saveContent(section, body);
    return new Response(JSON.stringify({ ok: true, data: saved }), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (err) {
    console.error('[content] validation_failed', section, err);
    const message = err instanceof Error && err.name === 'ZodError' ? err.message : undefined;
    return new Response(
      JSON.stringify(message ? { error: 'validation_failed', message } : { error: 'validation_failed' }),
      { status: 400 },
    );
  }
};
