import { q as query } from '../../../../chunks/db_Du3AmLCY.mjs';
export { renderers } from '../../../../renderers.mjs';

const GET = async ({ url }) => {
  try {
    const id = url.searchParams.get("id");
    if (id) {
      const result2 = await query("SELECT * FROM email_templates WHERE id = $1", [id]);
      if (!result2.rows.length) return Response.json({ error: "Not found" }, { status: 404 });
      return Response.json(result2.rows[0]);
    }
    const result = await query("SELECT id, name, type, created_at, updated_at FROM email_templates ORDER BY updated_at DESC");
    return Response.json({ data: result.rows });
  } catch (err) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};
const POST = async ({ request }) => {
  try {
    const { name, type, blocks_json, html_cache } = await request.json();
    const result = await query(
      "INSERT INTO email_templates (name, type, blocks_json, html_cache) VALUES ($1, $2, $3, $4) RETURNING *",
      [name, type || "custom", JSON.stringify(blocks_json || []), html_cache || ""]
    );
    return Response.json(result.rows[0]);
  } catch (err) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};
const PUT = async ({ request }) => {
  try {
    const { id, name, type, blocks_json, html_cache } = await request.json();
    if (!id) return Response.json({ error: "id required" }, { status: 400 });
    const result = await query(
      "UPDATE email_templates SET name=$1, type=$2, blocks_json=$3, html_cache=$4, updated_at=NOW() WHERE id=$5 RETURNING *",
      [name, type, JSON.stringify(blocks_json), html_cache || "", id]
    );
    return Response.json(result.rows[0]);
  } catch (err) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};
const DELETE = async ({ url }) => {
  try {
    const id = url.searchParams.get("id");
    if (!id) return Response.json({ error: "id required" }, { status: 400 });
    await query("DELETE FROM email_templates WHERE id = $1", [id]);
    return Response.json({ ok: true });
  } catch (err) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  DELETE,
  GET,
  POST,
  PUT
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
