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,
        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;

    return NextResponse.json({
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        role: user.role,
        restaurant_id: user.restaurantId,
        branch_id: effectiveBranchId,
        preferred_language: user.preferredLanguage || 'en',
        restaurants: user.restId ? {
          id: user.restId,
          name: user.restName,
          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,
      },
    });
  })
);
