import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { navigationItems } from '@/shared/schema';
import { eq, and } from 'drizzle-orm';
import { getNavigationItems, getAllNavigationItems } from '@/lib/navigation';

const SITE_ID = process.env.SITE_ID || 'ten-sura-game.com';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const all = searchParams.get('all');
    
    let items = [];
    if (all === '1') {
      items = await getAllNavigationItems();
    } else {
      // Typically the client doesn't fetch live items via API (layout does it), but we support it just in case
      const menuLocation = searchParams.get('menuLocation');
      if (menuLocation) {
        items = await getNavigationItems(menuLocation);
      } else {
        return NextResponse.json({ error: 'menuLocation is required when all=1 is not provided' }, { status: 400 });
      }
    }
    
    return NextResponse.json({ items });
  } catch (error: any) {
    console.error('Error in GET navigation items:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { 
      label, 
      url, 
      itemType, 
      sourceId, 
      menuLocation, 
      parentId, 
      parentCategory,
      sortOrder, 
      isActive, 
      openInNewTab 
    } = body;

    if (!label || !menuLocation) {
      return NextResponse.json({ error: 'Label and menuLocation are required' }, { status: 400 });
    }

    const newItem = await db.insert(navigationItems).values({
      siteId: SITE_ID,
      label,
      url: url || null,
      itemType: itemType || 'custom_page',
      sourceId: sourceId || null,
      menuLocation,
      parentId: parentId || null,
      parentCategory: parentCategory || null,
      sortOrder: sortOrder || 0,
      isActive: isActive !== undefined ? isActive : true,
      openInNewTab: openInNewTab || false,
      createdAt: new Date(),
      updatedAt: new Date(),
    }).returning({ id: navigationItems.id });

    return NextResponse.json({ success: true, id: newItem[0].id });
  } catch (error: any) {
    console.error('Error creating navigation item:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');

    if (!id) {
      return NextResponse.json({ error: 'id is required' }, { status: 400 });
    }

    const numericId = parseInt(id, 10);
    if (isNaN(numericId)) {
      return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
    }

    await db.delete(navigationItems).where(
      and(eq(navigationItems.id, numericId), eq(navigationItems.siteId, SITE_ID))
    );

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('Error deleting navigation item:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
