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

// Simple Inquiry controller: GET (list), POST (create), DELETE (remove)
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') || '20');
    const search = searchParams.get('search');
    const sortField = searchParams.get('sortField') || 'createdAt';
    const sortOrder = searchParams.get('sortOrder') || 'desc';

    const skip = (page - 1) * limit;
    const query: any = {};

    if (search) {
      query.$or = [
        { firstName: { $regex: search, $options: 'i' } },
        { lastName: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } },
        { mobile: { $regex: search, $options: 'i' } },
        { orderNumber: { $regex: search, $options: 'i' } }
      ];
    }

    // Build sort object
    let sortObject: any = {};
    
    // Handle special case for 'state' field (needs population sorting)
    if (sortField === 'state') {
      // For state sorting, we need to sort after population or use aggregation
      // Option 1: Get data first, sort in memory (simpler for now)
      const data = await Inquiry.find(query)
        .skip(skip)
        .limit(limit)
        .populate('state', 'name');
      
      // Sort in memory by state name
      data.sort((a, b) => {
        const stateA = a.state && typeof a.state === 'object' ? a.state.name : '';
        const stateB = b.state && typeof b.state === 'object' ? b.state.name : '';
        
        if (sortOrder === 'asc') {
          return stateA.localeCompare(stateB);
        } else {
          return stateB.localeCompare(stateA);
        }
      });
      
      const total = await Inquiry.countDocuments(query);
      
      return NextResponse.json({ 
        success: true, 
        data, 
        pagination: { page, limit, total, pages: Math.ceil(total / limit) } 
      });
    } else {
      // For other fields, use MongoDB sorting
      sortObject[sortField] = sortOrder === 'asc' ? 1 : -1;
      
      const data = await Inquiry.find(query)
        .sort(sortObject)
        .skip(skip)
        .limit(limit)
        .populate('state', 'name');
      
      const total = await Inquiry.countDocuments(query);
      
      return NextResponse.json({ 
        success: true, 
        data, 
        pagination: { page, limit, total, pages: Math.ceil(total / limit) } 
      });
    }
  } catch (error: any) {
    console.error('Error fetching inquiries:', error);
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
} 

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

    const body = await request.json();
    const { firstName, lastName, email, mobile, state, orderNumber, feedback } = body;

    if (!firstName || !email || !mobile) {
      return NextResponse.json({ success: false, error: 'firstName, email and mobile are required' }, { status: 400 });
    }

    const inquiry = await Inquiry.create({ firstName, lastName, email, mobile, state, orderNumber, feedback });

    return NextResponse.json({ success: true, data: inquiry }, { status: 201 });
  } catch (error: any) {
    console.error('Error creating inquiry:', error);
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest) {
  try {
    await dbConnect();

    const url = new URL(request.url);
    const id = url.pathname.split('/').pop();
    if (!id) return NextResponse.json({ success: false, error: 'Inquiry ID is required' }, { status: 400 });

    const doc = await Inquiry.findById(id);
    if (!doc) return NextResponse.json({ success: false, error: 'Inquiry not found' }, { status: 404 });

    await Inquiry.findByIdAndDelete(id);

    return NextResponse.json({ success: true, message: 'Inquiry deleted' });
  } catch (error: any) {
    console.error('Error deleting inquiry:', error);
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}
