← back to Freddy

app/api/matches/route.ts

43 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 });
  }

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

    let sql = `
      SELECT m.id, m.cause_id, m.org_id, m.granter_id,
             m.match_score, m.cause_alignment, m.public_support, m.granter_fit,
             m.ai_reasoning, m.status, m.funding_amount, m.funded_at,
             m.created_at, m.updated_at,
             c.title as cause_title, c.urgency_score, c.category as cause_category,
             o.name as org_name, o.trust_score, o.impact_score,
             g.name as granter_name, g.annual_budget as granter_budget
      FROM matches m
      JOIN causes c ON c.id = m.cause_id
      JOIN organizations o ON o.id = m.org_id
      LEFT JOIN granters g ON g.id = m.granter_id
    `;
    const params: unknown[] = [];

    if (status) {
      params.push(status);
      sql += ` WHERE m.status = $${params.length}`;
    }

    sql += ' ORDER BY m.match_score DESC LIMIT 100';

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