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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const assetType = searchParams.get('asset_type');
    const search = searchParams.get('search');

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

    if (status && status !== 'all') {
      query += ` AND status = $${paramIndex++}`;
      params.push(status);
    }
    if (assetType && assetType !== 'all') {
      query += ` AND asset_type = $${paramIndex++}`;
      params.push(assetType);
    }
    if (search) {
      query += ` AND (address ILIKE $${paramIndex} OR market ILIKE $${paramIndex})`;
      params.push(`%${search}%`);
      paramIndex++;
    }

    query += ' ORDER BY created_at DESC';

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

export async function POST(request: NextRequest) {
  try {
    const session = await getSessionUser();
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const {
      address, asset_type, asking_price, cap_rate, noi,
      sqft, units, year_built, market, city, state, notes
    } = body;

    if (!address || !asset_type || !market) {
      return NextResponse.json({ error: 'Address, asset type, and market are required' }, { status: 400 });
    }

    // Extract city/state from market if not provided
    const marketParts = market.split(', ');
    const derivedCity = city || marketParts[0] || null;
    const derivedState = state || marketParts[1] || null;

    const result = await pool.query(
      `INSERT INTO seller_leads (agent_id, address, asset_type, asking_price, cap_rate, noi, sqft, units, year_built, market, city, state, notes)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
       RETURNING *`,
      [session.id, address, asset_type, asking_price || null, cap_rate || null, noi || null,
       sqft || null, units || null, year_built || null, market, derivedCity, derivedState, notes || null]
    );

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