import type { APIRoute } from 'astro';
import { getDb } from '../../../../lib/db';
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 = () => {
  const rows = getDb().prepare(
    'SELECT tag, type, value, styles, updated_at, updated_by FROM content_blocks ORDER BY tag'
  ).all() as { tag: string; type: string; value: string; styles: string; updated_at: string; updated_by: string | null }[];
  const items = rows.map((r) => {
    let styles: Record<string, string> = {};
    try { styles = JSON.parse(r.styles); } catch { /* styles corrotto: si ignora */ }
    if (typeof styles !== 'object' || styles === null) styles = {};
    return {
      tag: r.tag,
      type: r.type,
      value: r.value,
      styles,
      styleOptions: seedByTag.get(r.tag)?.styleOptions ?? [],
      updatedAt: r.updated_at,
      updatedBy: r.updated_by,
    };
  });
  return json(200, { items });
};
