← back to Patty

app/api/templates/route.ts

63 lines

import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { verifyAuth } from '@/lib/auth';

export async function GET(request: NextRequest) {
  const user = verifyAuth(request);
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const url = new URL(request.url);
  const category = url.searchParams.get('category');

  let sql = `SELECT * FROM petition_templates`;
  const params: unknown[] = [];

  if (category && category !== 'all') {
    params.push(category);
    sql += ` WHERE category = $${params.length}`;
  }

  sql += ` ORDER BY is_featured DESC, usage_count DESC, created_at DESC`;

  try {
    const result = await query(sql, params);
    return NextResponse.json({ rows: result.rows });
  } catch (err) {
    console.error('[api/templates] GET error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to fetch templates' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  const user = verifyAuth(request);
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const body = await request.json();
    const { title, category, body_html, body_text, tags, is_featured } = body;

    if (!title || !body_html) {
      return NextResponse.json({ error: 'Title and body_html are required' }, { status: 400 });
    }

    const result = await query(
      `INSERT INTO petition_templates (title, category, body_html, body_text, tags, is_featured)
       VALUES ($1, $2, $3, $4, $5, $6)
       RETURNING *`,
      [
        title,
        category || null,
        body_html,
        body_text || null,
        tags || null,
        is_featured || false,
      ]
    );

    return NextResponse.json({ row: result.rows[0] }, { status: 201 });
  } catch (err) {
    console.error('[api/templates] POST error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to create template' }, { status: 500 });
  }
}