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

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8001';
const DB_URL = process.env.DATABASE_URL || 'postgresql://scraper:scraper123@localhost:5437/scraper';

// Direct database query for categories
async function fetchCategoriesFromDB() {
  // For now, we'll fetch from the API server which has DB access
  // In production, you might want to use a direct DB connection or cache
  const response = await fetch(`${API_BASE_URL}/categories/tree`, {
    cache: 'no-store',
  });

  if (!response.ok) {
    throw new Error('Failed to fetch categories from API');
  }

  return response.json();
}

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const search = searchParams.get('search');
    const parentPath = searchParams.get('parent');
    const level = searchParams.get('level');

    // Build query params for backend
    const params = new URLSearchParams();
    if (search) params.set('search', search);
    if (parentPath) params.set('parent', parentPath);
    if (level) params.set('level', level);

    const url = `${API_BASE_URL}/categories?${params.toString()}`;

    const response = await fetch(url, {
      cache: 'no-store',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      // Fallback: return mock data for development
      console.error('API not available, returning mock data');
      return NextResponse.json({
        categories: [],
        total: 0,
        message: 'API not available'
      });
    }

    const data = await response.json();
    return NextResponse.json(data);

  } catch (error) {
    console.error('Error fetching categories:', error);
    return NextResponse.json(
      { error: 'Failed to fetch categories', categories: [], total: 0 },
      { status: 500 }
    );
  }
}
