import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import Leads from '../../src/models/Leads';
import '@/models/State'

export async function GET(request: NextRequest) {
  try {
    await dbConnect();
    
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const search = searchParams.get('search');
    const sort = searchParams.get('sort') || 'createdAt';
    const order = searchParams.get('order') || 'desc';

    let query: any = {};

    // Search functionality - search by name or phone number
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { phone_number: { $regex: search, $options: 'i' } },
        
      ];
    }

    const skip = (page - 1) * limit;
    const sortOrder = order === 'asc' ? 1 : -1;

    // Create sort object based on field
    let sortObject: any = {};
    
    switch (sort) {
      case 'name':
        sortObject = { name: sortOrder };
        break;
      case 'phone_number':
        sortObject = { phone_number: sortOrder };
        break;
      case 'createdAt':
      default:
        sortObject = { createdAt: sortOrder };
        break;
    }

    const leads = await Leads.find(query)
      .sort(sortObject)
      .populate('state')
      .skip(skip)
      .limit(limit)
      .lean();

    const total = await Leads.countDocuments(query);
    
    return NextResponse.json({
      success: true,
      data: leads,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });
    
  } catch (error: any) {
    console.error("Error fetching leads:", error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    await dbConnect();

    const body = await req.json();

    const existing = await Leads.findOne({
      phone_number: body.phone_number
    });

    if (existing) {
      return NextResponse.json({
        success: true,
        data: existing,
        message: "Lead already exists"
      });
    }

    const lead = await Leads.create(body);

    return NextResponse.json({
      success: true,
      data: lead,
      message: "Lead saved successfully"
    });

  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err.message },
      { status: 500 }
    );
  }
}