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 o.*, r.name AS restaurant_name, b.name AS branch_name,
     *        c.name AS customer_full_name, c.email AS customer_full_email
     * FROM orders o LEFT JOIN restaurants r ON ... LEFT JOIN branches b ON ... LEFT JOIN customers c ON ...
     * WHERE o.id = $1
     */
    const { rows } = await db.execute(sql`
      SELECT
        o.*,
        r.name AS restaurant_name,
        b.name AS branch_name,
        c.name AS customer_full_name,
        c.email AS customer_full_email
      FROM orders o
      LEFT JOIN restaurants r ON o.restaurant_id = r.id
      LEFT JOIN branches b ON o.branch_id = b.id
      LEFT JOIN customers c ON o.customer_id = c.id
      WHERE o.id = ${id}
    `);
    const row = rows[0];
    if (!row) throw new NotFoundError('Order');
    return NextResponse.json({ order: row });
  })
);
