// src/app/api/orders/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  try {
    // Parse the request body
    const body = await request.json();
    
    // Validate required fields
    if (!body.user_id) {
      return NextResponse.json(
        { message: 'User ID is required' },
        { status: 400 }
      );
    }
    
    if (!body.total_amount && body.total_amount !== 0) {
      return NextResponse.json(
        { message: 'Total amount is required' },
        { status: 400 }
      );
    }
    
    if (!body.status) {
      return NextResponse.json(
        { message: 'Status is required' },
        { status: 400 }
      );
    }
    
    if (!body.selected_options) {
      return NextResponse.json(
        { message: 'Selected options are required' },
        { status: 400 }
      );
    }
    
    // Make API request to backend
    const response = await fetch(`${process.env.BACKEND_URL }/api/v1/orders`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        // Add authorization if needed
        // 'Authorization': `Bearer ${token}`,
      },
      body: JSON.stringify({
        user_id: body.user_id,
        total_amount: body.total_amount,
        status: body.status,
        selected_options: body.selected_options, // Send as an object, not as JSON string
        whmcs_invoice_id: null // Set to null as requested
      }),
    });
    
    // Check if the request was successful
    if (!response.ok) {
      const errorData = await response.json();
      return NextResponse.json(
        { message: errorData.message || 'Failed to create order' },
        { status: response.status }
      );
    }
    
    // Return the response data
    const data = await response.json();
    return NextResponse.json(data);
    
  } catch (error) {
    console.error('Error creating order:', error);
    return NextResponse.json(
      { message: error instanceof Error ? error.message : 'An error occurred while creating the order' },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    // Make API request to backend to get all orders
    const response = await fetch(`${process.env.BACKEND_URL }/api/v1/orders`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        // Add authorization if needed
        // 'Authorization': `Bearer ${token}`,
      },
    });
    
    // Check if the request was successful
    if (!response.ok) {
      const errorData = await response.json();
      return NextResponse.json(
        { message: errorData.message || 'Failed to fetch orders' },
        { status: response.status }
      );
    }
    
    // Return the response data
    const data = await response.json();
    return NextResponse.json(data);
    
  } catch (error) {
    console.error('Error fetching orders:', error);
    return NextResponse.json(
      { message: error instanceof Error ? error.message : 'An error occurred while fetching orders' },
      { status: 500 }
    );
  }
}
