import { NextResponse } from 'next/server';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { parseListParams, buildListEnvelope, CursorError, cursorErrorResponse } from '@server/middleware/v1Pagination';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';

export const GET = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest) => {
    const url = new URL(req.url);
    let pager;
    try { pager = parseListParams(url, 50, 200); }
    catch (e) { if (e instanceof CursorError) return cursorErrorResponse(e); throw e; }

    const { restaurantId } = req.apiKey;
    await initDatabase();

    const offset = (pager.page - 1) * pager.limit;
    const includeInactive = url.searchParams.get('include_inactive') === 'true';
    const conditions = includeInactive
      ? sql`restaurant_id = ${restaurantId}`
      : sql`restaurant_id = ${restaurantId} AND is_active = true`;

    /* raw: SELECT id, name, address, phone, timezone, is_active, hours,
            accepts_dine_in, accepts_takeaway, accepts_delivery,
            storefront_enabled, slug, min_order_value, created_at, updated_at
       FROM branches WHERE restaurant_id = $1 [AND is_active = true]
       ORDER BY name ASC LIMIT $2 OFFSET $3 */
    const { rows } = await db.execute(sql`
      SELECT id, name, address, phone, timezone, is_active, hours,
             accepts_dine_in, accepts_takeaway, accepts_delivery,
             storefront_enabled, slug, min_order_value, created_at, updated_at
        FROM branches
       WHERE ${conditions}
       ORDER BY name ASC
       LIMIT ${pager.limit} OFFSET ${offset}
    `);

    return NextResponse.json(buildListEnvelope(rows, pager.page, pager.limit));
  }, { permission: 'menu:read' })
);
