import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, NotFoundError } from '@server/errors';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    await initDatabase();
    const { id } = await ctx.params;

    /* raw:
     * SELECT b.*, r.name AS restaurant_name, br.name AS branch_name,
     *        c.name AS customer_full_name, c.email AS customer_full_email
     * FROM bookings b LEFT JOIN restaurants r ON ... LEFT JOIN branches br ON ... LEFT JOIN customers c ON ...
     * WHERE b.id = $1
     */
    const { rows } = await db.execute(sql`
      SELECT
        b.*,
        r.name AS restaurant_name,
        br.name AS branch_name,
        c.name AS customer_full_name,
        c.email AS customer_full_email
      FROM bookings b
      LEFT JOIN restaurants r ON b.restaurant_id = r.id
      LEFT JOIN branches br ON b.branch_id = br.id
      LEFT JOIN customers c ON b.customer_id = c.id
      WHERE b.id = ${id}
    `);
    const row = rows[0];
    if (!row) throw new NotFoundError('Booking');
    return NextResponse.json({ booking: row });
  })
);
