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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const { restaurantId } = req.session;
    if (!restaurantId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const rows = await db.select({
      name: restaurants.name,
      cuisine_type: restaurants.cuisineType,
      phone: restaurants.phone,
      address: restaurants.address,
      description: restaurants.description,
      seating_capacity: restaurants.seatingCapacity,
    })
    .from(restaurants)
    .where(eq(restaurants.id, restaurantId));
    const row = rows[0];

    if (!row) {
      return NextResponse.json({ error: 'Restaurant not found' }, { status: 404 });
    }

    return NextResponse.json({ profile: row });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const { restaurantId } = req.session;
    if (!restaurantId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json().catch(() => ({}));
    const { name, cuisine_type, phone, address, description, seating_capacity } = body as {
      name?: string;
      cuisine_type?: string;
      phone?: string;
      address?: string;
      description?: string;
      seating_capacity?: number;
    };

    if (name !== undefined && (typeof name !== 'string' || name.trim().length === 0)) {
      return NextResponse.json({ error: 'Restaurant name cannot be empty' }, { status: 400 });
    }

    if (seating_capacity !== undefined && seating_capacity !== null) {
      const cap = Number(seating_capacity);
      if (!Number.isInteger(cap) || cap < 0) {
        return NextResponse.json({ error: 'Seating capacity must be a non-negative integer' }, { status: 400 });
      }
    }

    const sets: SQL[] = [];

    if (name !== undefined) sets.push(sql`name = ${name.trim()}`);
    if ('cuisine_type' in body) sets.push(sql`cuisine_type = ${cuisine_type?.trim() || null}`);
    if ('phone' in body) sets.push(sql`phone = ${phone?.trim() || null}`);
    if ('address' in body) sets.push(sql`address = ${address?.trim() || null}`);
    if ('description' in body) sets.push(sql`description = ${description?.trim() || null}`);
    if ('seating_capacity' in body) {
      sets.push(sql`seating_capacity = ${seating_capacity !== undefined && seating_capacity !== null ? Math.floor(Number(seating_capacity)) : null}`);
    }

    if (sets.length === 0) {
      return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
    }

    sets.push(sql`updated_at = NOW()`);

    const { rows } = await db.execute(sql`
      UPDATE restaurants SET ${sql.join(sets, sql`, `)}
      WHERE id = ${restaurantId}
      RETURNING name, cuisine_type, phone, address, description, seating_capacity
    `);
    const result = rows[0];

    if (!result) {
      return NextResponse.json({ error: 'Restaurant not found' }, { status: 404 });
    }

    return NextResponse.json({ profile: result });
  })
);
