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

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

export async function POST(request: Request) {
  try {
    const { items = [], deletedIds = [] } = await request.json();

    // Start a transaction if needed, but Drizzle SQLite/Neon support for it can vary.
    // We will do it sequentially as a safe three-step approach.

    // 1. DELETE
    if (deletedIds.length > 0) {
      await db.delete(navigationItems).where(
        and(
          inArray(navigationItems.id, deletedIds),
          eq(navigationItems.siteId, SITE_ID)
        )
      );
    }

    // Prepare items for Upsert/Insert
    const existingItems = items.filter((item: any) => item.id && item.id > 0);
    const newItems = items.filter((item: any) => !item.id || item.id <= 0);

    // 2. UPSERT (Update existing)
    for (const item of existingItems) {
      await db.update(navigationItems)
        .set({
          label: item.label,
          url: item.url || null,
          menuLocation: item.menuLocation,
          parentId: item.parentId || null,
          parentCategory: item.parentCategory || null,
          sortOrder: item.sortOrder || 0,
          isActive: item.isActive !== undefined ? item.isActive : true,
          updatedAt: new Date(),
        })
        .where(
          and(
            eq(navigationItems.id, item.id),
            eq(navigationItems.siteId, SITE_ID)
          )
        );
    }

    // 3. INSERT (Create new)
    if (newItems.length > 0) {
      const insertValues = newItems.map((item: any) => ({
        siteId: SITE_ID,
        label: item.label,
        url: item.url || null,
        itemType: item.itemType || 'custom_page',
        sourceId: item.sourceId || null,
        menuLocation: item.menuLocation,
        parentId: item.parentId || null,
        parentCategory: item.parentCategory || null,
        sortOrder: item.sortOrder || 0,
        isActive: item.isActive !== undefined ? item.isActive : true,
        openInNewTab: item.openInNewTab || false,
        createdAt: new Date(),
        updatedAt: new Date(),
      }));
      
      await db.insert(navigationItems).values(insertValues);
    }

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('Error in bulk-save navigation items:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
