import { NextRequest, NextResponse } from 'next/server';
import { nocodbClient } from '@/api/nocodbClient';
import type { OrderFilters, PaginationParams } from '@/api/nocodbClient';

/**
 * GET /api/admin/orders
 * Get list of orders with filtering, sorting, and pagination
 * Query params:
 *   - search: Text search across vessel name, IMO, order ID
 *   - status: Filter by order status
 *   - dateFrom, dateTo: Date range filter
 *   - limit: Page size (default: 50)
 *   - offset: Pagination offset
 *   - sortBy: Field to sort by
 *   - sortOrder: 'asc' | 'desc'
 */
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const searchTerm = searchParams.get('search');

    // Build filters
    const filters: OrderFilters = {};
    if (searchParams.get('status')) filters.status = searchParams.get('status')!;
    if (searchParams.get('dateFrom')) filters.dateFrom = searchParams.get('dateFrom')!;
    if (searchParams.get('dateTo')) filters.dateTo = searchParams.get('dateTo')!;
    if (searchParams.get('vesselName')) filters.vesselName = searchParams.get('vesselName')!;
    if (searchParams.get('imoNumber')) filters.imoNumber = searchParams.get('imoNumber')!;

    // Build pagination
    const pagination: PaginationParams = {
      limit: parseInt(searchParams.get('limit') || '50'),
      offset: parseInt(searchParams.get('offset') || '0'),
      sortBy: searchParams.get('sortBy') || 'CreatedAt',
      sortOrder: (searchParams.get('sortOrder') as 'asc' | 'desc') || 'desc',
    };

    // Use search if provided, otherwise use filters
    const response = searchTerm
      ? await nocodbClient.searchOrders(searchTerm, pagination)
      : await nocodbClient.getOrders(filters, pagination);

    return NextResponse.json({
      success: true,
      data: response.list,
      pagination: response.pageInfo,
    });
  } catch (error) {
    console.error('Error fetching orders:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to fetch orders',
      },
      { status: 500 }
    );
  }
}

/**
 * POST /api/admin/orders
 * Create a new order (if needed for manual entry)
 */
export async function POST(_request: NextRequest) {
  try {
    // In a real implementation, you'd call nocodbClient to create the order
    // For now, return a placeholder
    return NextResponse.json(
      {
        success: false,
        error: 'Order creation not yet implemented',
      },
      { status: 501 }
    );
  } catch (error) {
    console.error('Error creating order:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to create order',
      },
      { status: 500 }
    );
  }
}
