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 channel = searchParams.get('channel');
    const status = searchParams.get('status');
    const search = searchParams.get('search');

    let query = `
      SELECT o.*,
        json_build_object(
          'id', m.id, 'lead_id', m.lead_id, 'buyer_id', m.buyer_id,
          'match_score', m.match_score, 'status', m.status,
          'seller_lead', json_build_object(
            'id', sl.id, 'address', sl.address, 'asset_type', sl.asset_type,
            'market', sl.market, 'asking_price', sl.asking_price
          ),
          'buyer', json_build_object(
            'id', b.id, 'name', b.name, 'company', b.company, 'email', b.email
          )
        ) as match
      FROM outreach o
      JOIN matches m ON o.match_id = m.id
      JOIN seller_leads sl ON m.lead_id = sl.id
      JOIN buyers b ON m.buyer_id = b.id
      WHERE 1=1
    `;

    const params: unknown[] = [];
    let paramIndex = 1;

    if (channel && channel !== 'all') {
      query += ` AND o.channel = $${paramIndex++}`;
      params.push(channel);
    }
    if (status && status !== 'all') {
      query += ` AND o.status = $${paramIndex++}`;
      params.push(status);
    }
    if (search) {
      query += ` AND (o.subject ILIKE $${paramIndex} OR b.name ILIKE $${paramIndex})`;
      params.push(`%${search}%`);
      paramIndex++;
    }

    query += ' ORDER BY o.created_at DESC';

    const result = await pool.query(query, params);
    return NextResponse.json(result.rows);
  } catch (error) {
    console.error('Outreach GET error:', error);
    return NextResponse.json({ error: 'Failed to fetch outreach' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { match_id, channel, subject, body: messageBody } = body;

    if (!match_id || !channel || !messageBody) {
      return NextResponse.json({ error: 'match_id, channel, and body are required' }, { status: 400 });
    }

    const result = await pool.query(
      `INSERT INTO outreach (match_id, channel, subject, body, status, sent_at)
       VALUES ($1, $2, $3, $4, 'sent', NOW())
       RETURNING *`,
      [match_id, channel, subject || null, messageBody]
    );

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