import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';

const API_BASE_URL = process.env.API_BASE_URL || "https://admin.mymorni.com/api/v1";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return handleRequest(req, path, 'GET');
}

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return handleRequest(req, path, 'POST');
}

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return handleRequest(req, path, 'PUT');
}

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return handleRequest(req, path, 'DELETE');
}

async function handleRequest(
  req: NextRequest,
  path: string[],
  method: string
) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('token')?.value;

    if (!token) {
      console.error('Proxy API: No token found in cookies');
      return NextResponse.json(
        { success: false, message: 'Unauthorized - Please login' },
        { status: 401 }
      );
    }

    // Build the full endpoint path
    const endpoint = path.join('/');
    const url = new URL(`${API_BASE_URL}/${endpoint}`);
    
    // Copy query parameters
    req.nextUrl.searchParams.forEach((value, key) => {
      url.searchParams.append(key, value);
    });

    console.log(`Proxy API: ${method} ${url.toString()}`);

    // Prepare fetch options
    const fetchOptions: RequestInit = {
      method,
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    };

    // Include body for POST, PUT, PATCH, DELETE
    if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
      const contentType = req.headers.get('content-type');
      
      // Handle FormData (multipart/form-data)
      if (contentType?.includes('multipart/form-data') || !contentType) {
        // For FormData, pass the request body directly without setting Content-Type
        // (browser/fetch will set it with the boundary automatically)
        const formData = await req.formData();
        fetchOptions.body = formData as any;
      } else {
        // Handle JSON or other content types
        fetchOptions.headers = {
          ...fetchOptions.headers,
          'Content-Type': 'application/json',
        };
        const body = await req.text();
        if (body) {
          fetchOptions.body = body;
        }
      }
    }

    // Forward request to backend
    const response = await fetch(url.toString(), fetchOptions);
    
    // Check if response is JSON
    const contentType = response.headers.get('content-type');
    if (!contentType || !contentType.includes('application/json')) {
      console.error(`Proxy API: Backend returned non-JSON response (${response.status})`);
      const text = await response.text();
      console.error('Response body:', text.substring(0, 200));
      return NextResponse.json(
        { success: false, message: `Backend returned non-JSON response (${response.status})` },
        { status: response.status }
      );
    }
    
    const data = await response.json();

    if (!response.ok) {
      console.error(`Proxy API: Backend error (${response.status}):`, data.message || data);
    }

    return NextResponse.json(data, { status: response.status });
  } catch (error: any) {
    console.error('Proxy API error:', error);
    return NextResponse.json(
      { success: false, message: error.message || 'Internal server error' },
      { status: 500 }
    );
  }
}
