← back to Norma

app/api/collaborations/route.ts

109 lines

import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';
import { getOrgId } from '@/lib/orgId';

/**
 * GET /api/collaborations?type=nonprofit|politician|corporation|municipality&limit=&offset=
 * Returns collaboration suggestions filtered by type. Supports pagination.
 */
export async function GET(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  const { searchParams } = new URL(request.url);
  const collabType = searchParams.get('type');
  const status = searchParams.get('status');
  const orgId = auth.role === 'admin' ? getOrgId(request) : auth.orgId;

  let limit = parseInt(searchParams.get('limit') || '50', 10);
  if (isNaN(limit) || limit < 1) limit = 50;
  if (limit > 200) limit = 200;

  let offset = parseInt(searchParams.get('offset') || '0', 10);
  if (isNaN(offset) || offset < 0) offset = 0;

  const conditions: string[] = [];
  const params: unknown[] = [];
  let idx = 1;

  if (orgId) {
    conditions.push(`org_id = $${idx++}`);
    params.push(orgId);
  }
  if (collabType) {
    conditions.push(`collab_type = $${idx++}`);
    params.push(collabType);
  }
  if (status) {
    conditions.push(`status = $${idx++}`);
    params.push(status);
  }

  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

  try {
    const countResult = await query(
      `SELECT COUNT(*)::int AS total FROM collaborations ${whereClause}`,
      params
    );
    const total = countResult.rows[0]?.total ?? 0;

    const { rows } = await query(
      `SELECT * FROM collaborations ${whereClause}
       ORDER BY ai_relevance DESC NULLS LAST, created_at DESC
       LIMIT $${idx} OFFSET $${idx + 1}`,
      [...params, limit, offset]
    );
    return NextResponse.json({ collaborations: rows, total, limit, offset });
  } catch (err) {
    console.error('[collaborations] GET error:', (err as Error).message);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

/**
 * POST /api/collaborations
 * Create a new collaboration entry manually or via AI discovery.
 */
export async function POST(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  try {
    const body = await request.json();
    const {
      collab_type, name, title, organization, website_url,
      email, phone, district, state, city, party,
      committees, focus_areas, ai_reason, ai_relevance,
      ai_talking_points, status: collabStatus, notes,
    } = body;

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

    const orgId = auth.role === 'admin' ? getOrgId(request) : auth.orgId;
    const { rows } = await query(
      `INSERT INTO collaborations (
        collab_type, name, title, organization, website_url,
        email, phone, district, state, city, party,
        committees, focus_areas, ai_reason, ai_relevance,
        ai_talking_points, status, notes, org_id
      ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)
      RETURNING *`,
      [
        collab_type, name, title || null, organization || null, website_url || null,
        email || null, phone || null, district || null, state || null, city || null, party || null,
        committees || null, focus_areas || null, ai_reason || null, ai_relevance || null,
        ai_talking_points || null, collabStatus || 'suggested', notes || null, orgId,
      ]
    );

    return NextResponse.json({ collaboration: rows[0] });
  } catch (err) {
    console.error('[collaborations] POST error:', (err as Error).message);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}