import type { APIRoute } from 'astro';
import { getDb } from '../../../../lib/db';
import { applyContentUpdate } from '../../../../lib/content-update';
import { invalidateContentCache } from '../../../../lib/content';
import { seedByTag } from '../../../../data/content-seed';
export const prerender = false;

const json = (status: number, body: object) =>
  new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });

export const GET: APIRoute = ({ params }) => {
  const tag = params.tag ?? '';
  const row = getDb().prepare('SELECT tag, type, value, styles, guid FROM content_blocks WHERE tag = ?').get(tag) as
    { tag: string; type: string; value: string; styles: string; guid: string | null } | undefined;
  if (!row) return json(404, { error: 'Tag inesistente.' });
  let styles: Record<string, string> = {};
  try {
    const parsed = JSON.parse(row.styles);
    if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) styles = parsed;
  } catch { /* styles corrotto: si ignora */ }
  return json(200, {
    tag: row.tag,
    guid: row.guid ?? '',
    type: row.type,
    value: row.value,
    styles,
    styleOptions: seedByTag.get(row.tag)?.styleOptions ?? [],
  });
};

export const PUT: APIRoute = async ({ params, request, locals }) => {
  let data: Record<string, unknown>;
  try { data = await request.json(); } catch { return json(400, { error: 'Dati non validi.' }); }
  if (typeof data !== 'object' || data === null) return json(400, { error: 'Dati non validi.' });
  const r = applyContentUpdate(getDb(), params.tag ?? '', data, locals.user!.username);
  if (!r.ok) return json(r.status, { error: r.error });
  invalidateContentCache();
  // Il value salvato può differire da quello inviato (sanitizeInline sui tag html):
  // lo restituiamo così il pannello mostra il dato reale.
  const row = getDb().prepare('SELECT value FROM content_blocks WHERE tag = ?').get(params.tag) as { value: string };
  return json(200, { ok: true, value: row.value });
};
