import type { APIRoute } from 'astro';
import { query } from '../../../../lib/db';

export const GET: APIRoute = async ({ url }) => {
  try {
    const id = url.searchParams.get('id');
    if (id) {
      const result = await query('SELECT * FROM email_templates WHERE id = $1', [id]);
      if (!result.rows.length) return Response.json({ error: 'Not found' }, { status: 404 });
      return Response.json(result.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: any) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};

export const POST: APIRoute = 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: any) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};

export const PUT: APIRoute = 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: any) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};

export const DELETE: APIRoute = 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: any) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};
