import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const buyerId = searchParams.get('buyer_id');
    const leadId = searchParams.get('lead_id');

    let query = 'SELECT * FROM ndas WHERE 1=1';
    const params: unknown[] = [];
    let idx = 1;

    if (buyerId) {
      query += ` AND buyer_id = $${idx++}`;
      params.push(buyerId);
    }
    if (leadId) {
      query += ` AND lead_id = $${idx++}`;
      params.push(leadId);
    }

    query += ' ORDER BY signed_at DESC';
    const result = await pool.query(query, params);
    return NextResponse.json(result.rows);
  } catch (error) {
    console.error('NDAs GET error:', error);
    return NextResponse.json({ error: 'Failed to fetch NDAs' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { buyer_id, lead_id, signer_name, signer_email, signer_company } = body;

    if (!buyer_id || !lead_id || !signer_name || !signer_email) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
    const ua = request.headers.get('user-agent') || 'unknown';

    const result = await pool.query(
      `INSERT INTO ndas (buyer_id, lead_id, signer_name, signer_email, signer_company, ip_address, user_agent)
       VALUES ($1, $2, $3, $4, $5, $6, $7)
       ON CONFLICT (buyer_id, lead_id) DO UPDATE SET signed_at = NOW()
       RETURNING *`,
      [buyer_id, lead_id, signer_name, signer_email, signer_company || null, ip, ua]
    );

    return NextResponse.json(result.rows[0], { status: 201 });
  } catch (error) {
    console.error('NDA POST error:', error);
    return NextResponse.json({ error: 'Failed to create NDA' }, { status: 500 });
  }
}
