import { NextResponse } from 'next/server';
import { eq, and, sql } from 'drizzle-orm';
import { db, users, restaurants, branches } from '@server/db/drizzle';
import { initDatabase } from '@server/db/init';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const { userId, branchId: sessionBranchId } = req.session;

    const rows = await db
      .select({
        id: users.id,
        email: users.email,
        name: users.name,
        role: users.role,
        restaurantId: users.restaurantId,
        branchId: users.branchId,
        preferredLanguage: users.preferredLanguage,
        restId: restaurants.id,
        restName: restaurants.name,
        restSlug: restaurants.slug,
        restLogoUrl: restaurants.logoUrl,
        restCuisineType: restaurants.cuisineType,
        restPhone: restaurants.phone,
        restAddress: restaurants.address,
        restDescription: restaurants.description,
        restSeatingCapacity: restaurants.seatingCapacity,
        restCurrency: restaurants.currency,
        restCurrencySetAt: restaurants.currencySetAt,
        brId: branches.id,
        brName: branches.name,
      })
      .from(users)
      .leftJoin(restaurants, eq(users.restaurantId, restaurants.id))
      .leftJoin(
        branches,
        sessionBranchId
          ? eq(branches.id, sql`${sessionBranchId}::uuid`)
          : eq(branches.id, users.branchId)
      )
      .where(and(eq(users.id, userId), eq(users.isActive, true)));

    const user = rows[0];
    if (!user) return NextResponse.json({ user: null });

    const effectiveBranchId = sessionBranchId ?? user.branchId;

    // Fetch staff section permissions for non-owner roles so the client
    // can gate sidebar navigation without a separate round-trip.
    let staffPermissions: Record<string, Record<string, boolean>> | null = null;
    const role = req.session.role;
    if (
      role !== 'owner' &&
      role !== 'superadmin' &&
      role !== 'support' &&
      user.restaurantId
    ) {
      const { rows: staffRows } = await db.execute(sql`
        SELECT permissions FROM staff
        WHERE user_id = ${userId} AND restaurant_id = ${user.restaurantId}
        LIMIT 1
      `);
      const staffRow = staffRows[0] as { permissions?: Record<string, Record<string, boolean>> } | undefined;
      staffPermissions = staffRow?.permissions ?? null;
    }

    return NextResponse.json({
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        role: user.role,
        restaurant_id: user.restaurantId,
        branch_id: effectiveBranchId,
        // The literal JWT session branch, distinct from the coalesced
        // `branch_id` above. Owners in the "All branches" view get
        // `session_branch_id: null` here; the topbar uses this to know it
        // shouldn't pick a default branch on reload. Non-owners are
        // hard-pinned, so this matches their pinned branch.
        session_branch_id: sessionBranchId ?? null,
        preferred_language: user.preferredLanguage || 'en',
        staff_permissions: staffPermissions,
        restaurants: user.restId ? {
          id: user.restId,
          name: user.restName,
          slug: user.restSlug || null,
          logo_url: user.restLogoUrl || null,
          cuisine_type: user.restCuisineType || null,
          phone: user.restPhone || null,
          address: user.restAddress || null,
          description: user.restDescription || null,
          seating_capacity: user.restSeatingCapacity ?? null,
          currency: user.restCurrency || null,
          currency_locked: !!user.restCurrencySetAt,
        } : null,
        branches: user.brId ? { id: user.brId, name: user.brName } : null,
      },
    });
  })
);
