import { db } from './db';
import { navigationItems } from '../shared/schema';
import { eq, and } from 'drizzle-orm';

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

export interface NavNode {
  id: string; // Either category slug or custom page sourceId
  label: string;
  url: string;
  itemType: string;
  isActive: boolean;
  openInNewTab: boolean;
  children: NavNode[];
}

export async function getNavigationItems(menuLocation: string | string[]) {
  const { inArray } = await import('drizzle-orm');
  try {
    const locations = Array.isArray(menuLocation) ? menuLocation : [menuLocation];
    return await db
      .select()
      .from(navigationItems)
      .where(
        and(
          eq(navigationItems.siteId, SITE_ID),
          inArray(navigationItems.menuLocation, locations),
          eq(navigationItems.isActive, true)
        )
      )
      .orderBy(navigationItems.sortOrder);
  } catch (error) {
    console.error('Error fetching navigation items:', error);
    return [];
  }
}

export async function getAllNavigationItems() {
  try {
    return await db
      .select()
      .from(navigationItems)
      .where(eq(navigationItems.siteId, SITE_ID))
      .orderBy(navigationItems.sortOrder);
  } catch (error) {
    console.error('Error fetching all navigation items:', error);
    return [];
  }
}

export function buildNavigationTree(items: any[], categories: any[]): NavNode[] {
  const treeMap = new Map<string, NavNode>();
  const roots: NavNode[] = [];

  // Initialize DB categories as root nodes in the map if they are NOT already synced as ghost rows
  const existingCatSlugs = new Set(
    items.filter(i => i.itemType === 'category').map(i => i.url.replace('/category/', ''))
  );
  
  for (const cat of categories) {
    if (existingCatSlugs.has(cat.slug)) continue; // Skip — already a ghost row

    const catNode: NavNode = {
      id: cat.slug,
      label: cat.name,
      url: `/category/${cat.slug}`,
      itemType: 'category',
      isActive: true,
      openInNewTab: false,
      children: [],
    };
    treeMap.set(cat.slug, catNode);
    roots.push(catNode); // Categories are top-level by default
  }

  // Initialize custom navigation items
  for (const item of items) {
    const id = item.sourceId || item.id.toString();
    const node: NavNode = {
      id,
      label: item.label,
      url: item.url || '#',
      itemType: item.itemType,
      isActive: item.isActive,
      openInNewTab: item.openInNewTab,
      children: [],
    };
    treeMap.set(id, node);
    // CRITICAL: Also add by the integer ID string so parentId lookups (which use integer IDs) work!
    treeMap.set(item.id.toString(), node);

    // Also register ghost categories under cat:slug for parentCategory lookups
    if (item.itemType === 'category' && item.url.startsWith('/category/')) {
      const catSlug = item.url.replace('/category/', '');
      treeMap.set(`cat:${catSlug}`, node);
      // Fallback for Phase 6 legacy references (just the slug itself)
      treeMap.set(catSlug, node);
    }
  }

  // Build the hierarchy for custom navigation items
  for (const item of items) {
    const id = item.sourceId || item.id.toString();
    const node = treeMap.get(id);
    if (!node) continue;

    let parentId = null;
    if (item.parentCategory) {
      parentId = treeMap.has(`cat:${item.parentCategory}`) ? `cat:${item.parentCategory}` : item.parentCategory;
    } else if (item.parentId) {
      parentId = item.parentId.toString();
    }

    if (parentId && treeMap.has(parentId)) {
      const parentNode = treeMap.get(parentId);
      parentNode?.children.push(node);
    } else {
      roots.push(node);
    }
  }

  return roots;
}
