← back to Freddy

app/api/organizations/route.ts

80 lines

import { NextRequest, NextResponse } from 'next/server';
import { query } 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 category = request.nextUrl.searchParams.get('category');
    const sort = request.nextUrl.searchParams.get('sort') || 'votes';

    let sql = `
      SELECT id, name, ein, mission, description, website_url, logo_url,
             city, state, category, focus_areas, year_founded, annual_budget,
             staff_size, impact_score, trust_score, total_votes,
             total_funding_received, status, verified_at, created_at, updated_at
      FROM organizations
      WHERE status IN ('verified', 'featured', 'pending')
    `;
    const params: unknown[] = [];

    if (category) {
      params.push(category);
      sql += ` AND category = $${params.length}`;
    }

    if (sort === 'impact') {
      sql += ' ORDER BY impact_score DESC';
    } else if (sort === 'trust') {
      sql += ' ORDER BY trust_score DESC';
    } else if (sort === 'funding') {
      sql += ' ORDER BY total_funding_received DESC';
    } else {
      sql += ' ORDER BY total_votes DESC';
    }

    sql += ' LIMIT 100';

    const result = await query(sql, params);
    return NextResponse.json({ organizations: result.rows });
  } catch (err) {
    console.error('[organizations] GET error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to fetch organizations' }, { 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 { name, ein, mission, description, website_url, city, state, category, focus_areas, year_founded, annual_budget, staff_size } = body;

    if (!name) {
      return NextResponse.json({ error: 'Organization name is required' }, { status: 400 });
    }

    const result = await query(
      `INSERT INTO organizations (name, ein, mission, description, website_url, city, state, category, focus_areas, year_founded, annual_budget, staff_size)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
       RETURNING *`,
      [name, ein || null, mission || null, description || null, website_url || null, city || null, state || null, category || 'other', focus_areas || [], year_founded || null, annual_budget || null, staff_size || null],
    );

    await auditLog('org.created', 'organization', result.rows[0].id, { name, user });

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