← back to Freddy

app/api/votes/route.ts

102 lines

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

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

  try {
    const cause_id = request.nextUrl.searchParams.get('cause_id');

    let sql: string;
    let params: unknown[];

    if (cause_id) {
      sql = `
        SELECT v.id, v.cause_id, v.org_id, v.weight, v.reason, v.created_at,
               o.name as org_name, c.title as cause_title
        FROM votes v
        JOIN organizations o ON o.id = v.org_id
        JOIN causes c ON c.id = v.cause_id
        WHERE v.cause_id = $1
        ORDER BY v.created_at DESC
        LIMIT 100
      `;
      params = [cause_id];
    } else {
      sql = `
        SELECT v.id, v.cause_id, v.org_id, v.weight, v.reason, v.created_at,
               o.name as org_name, c.title as cause_title
        FROM votes v
        JOIN organizations o ON o.id = v.org_id
        JOIN causes c ON c.id = v.cause_id
        ORDER BY v.created_at DESC
        LIMIT 100
      `;
      params = [];
    }

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

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

  const client = await getClient();

  try {
    const body = await request.json();
    const { cause_id, org_id, weight, reason } = body;

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

    await client.query('BEGIN');

    // Insert vote
    const result = await client.query(
      `INSERT INTO votes (cause_id, org_id, weight, reason)
       VALUES ($1, $2, $3, $4)
       RETURNING *`,
      [cause_id, org_id, weight || 1.0, reason || null],
    );

    // Update cause vote count
    await client.query(
      `UPDATE causes SET total_votes = total_votes + 1, total_supporters = total_supporters + 1 WHERE id = $1`,
      [cause_id],
    );

    // Update org vote count
    await client.query(
      `UPDATE organizations SET total_votes = total_votes + 1 WHERE id = $1`,
      [org_id],
    );

    await client.query('COMMIT');

    await auditLog('vote.cast', 'vote', result.rows[0].id, { cause_id, org_id, user });

    return NextResponse.json({ vote: result.rows[0] }, { status: 201 });
  } catch (err) {
    await client.query('ROLLBACK');
    console.error('[votes] POST error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to cast vote' }, { status: 500 });
  } finally {
    client.release();
  }
}