← back to Norma

app/api/datasource/[id]/route.ts

102 lines

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

// ─── GET /api/datasource/[id] ─────────────────────────────────────────────────

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  const { id } = await params;
  if (!id) {
    return NextResponse.json({ error: 'Missing id' }, { status: 400 });
  }

  try {
    // Try discovered_apis first
    const { rows: apiRows } = await query<Record<string, unknown>>(
      `SELECT * FROM discovered_apis WHERE id = $1 LIMIT 1`,
      [id],
    );
    if (apiRows.length > 0) {
      return NextResponse.json({ type: 'api', item: apiRows[0] });
    }

    // Try newspaper_frontpages
    const { rows: headlineRows } = await query<Record<string, unknown>>(
      `SELECT * FROM newspaper_frontpages WHERE id = $1 LIMIT 1`,
      [id],
    );
    if (headlineRows.length > 0) {
      return NextResponse.json({ type: 'headline', item: headlineRows[0] });
    }

    // Try nonprofit_statements
    const { rows: stmtRows } = await query<Record<string, unknown>>(
      `SELECT * FROM nonprofit_statements WHERE id = $1 LIMIT 1`,
      [id],
    );
    if (stmtRows.length > 0) {
      return NextResponse.json({ type: 'statement', item: stmtRows[0] });
    }

    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  } catch (err: unknown) {
    console.error('[api/datasource/[id] GET] Error:', (err as Error).message);
    return NextResponse.json({ error: (err as Error).message }, { status: 500 });
  }
}

// ─── PUT /api/datasource/[id] — update status ─────────────────────────────────

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  const { id } = await params;
  if (!id) {
    return NextResponse.json({ error: 'Missing id' }, { status: 400 });
  }

  try {
    const body = (await request.json()) as { status?: string; notes?: string };
    const { status, notes } = body;

    if (!status) {
      return NextResponse.json({ error: 'Missing status in body' }, { status: 400 });
    }

    const VALID_STATUSES = ['discovered', 'validated', 'active', 'failed', 'archived'];
    if (!VALID_STATUSES.includes(status)) {
      return NextResponse.json(
        { error: `Invalid status. Must be one of: ${VALID_STATUSES.join(', ')}` },
        { status: 400 },
      );
    }

    // Try updating discovered_apis
    const { rowCount: apiRowCount } = await query(
      `UPDATE discovered_apis
       SET status = $1, notes = COALESCE($2, notes), updated_at = NOW()
       WHERE id = $3`,
      [status, notes ?? null, id],
    );

    if ((apiRowCount ?? 0) > 0) {
      return NextResponse.json({ success: true, id, status, table: 'discovered_apis' });
    }

    return NextResponse.json({ error: 'Record not found in discovered_apis' }, { status: 404 });
  } catch (err: unknown) {
    console.error('[api/datasource/[id] PUT] Error:', (err as Error).message);
    return NextResponse.json({ error: (err as Error).message }, { status: 500 });
  }
}