/**
 * withSipFeature — gate route handlers behind FEATURE_SIP_ENABLED.
 * Returns 404 (not 403) when off so the SIP add-on appears not to exist.
 * Optionally also checks restaurants.sip_enabled when an authed handler is wrapped.
 */
import { NextResponse } from 'next/server';
import { isSipFeatureEnabled } from '@/shared/config/sip-feature';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import type { RouteHandler, RouteContext } from './withErrorHandler';
import type { AuthedRequest } from './withAuth';

export function withSipFeature(handler: RouteHandler): RouteHandler {
  return async (req, ctx) => {
    if (!isSipFeatureEnabled()) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }
    return handler(req, ctx);
  };
}

export async function isRestaurantSipEnabled(restaurantId: string): Promise<boolean> {
  if (!isSipFeatureEnabled()) return false;
  try {
    /* raw: SELECT sip_enabled FROM restaurants WHERE id = $1 */
    const { rows } = await db.execute(sql`SELECT sip_enabled FROM restaurants WHERE id = ${restaurantId}`);
    return Boolean((rows[0] as { sip_enabled?: boolean } | undefined)?.sip_enabled);
  } catch {
    return false;
  }
}

export function withSipFeatureAuthed<H extends (req: AuthedRequest, ctx: RouteContext) => Promise<NextResponse | Response>>(
  handler: H
): H {
  return (async (req: AuthedRequest, ctx: RouteContext) => {
    if (!isSipFeatureEnabled()) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }
    const restaurantId = req.session.restaurantId;
    if (restaurantId && !(await isRestaurantSipEnabled(restaurantId))) {
      return NextResponse.json({ error: 'SIP add-on not enabled for this restaurant' }, { status: 404 });
    }
    return handler(req, ctx);
  }) as H;
}
