import { NextResponse, type NextRequest } from 'next/server';
import { verifySession } from '@server/auth';
import { eq, desc } from 'drizzle-orm';
import { db, subscriptions } from '@server/db/drizzle';
import { initDatabase } from '@server/db/init';

const GATE_TTL_SECONDS = 300;
const COOKIE_NAME = 'restroagent_session';
const SUB_GATE_COOKIE = 'sub_gate';
const EXEMPT_ROLES = new Set(['superadmin', 'support']);

export async function GET(request: NextRequest) {
  const token = request.cookies.get(COOKIE_NAME)?.value;
  if (!token) {
    return NextResponse.json({ gate: 'unauthenticated' }, { status: 401 });
  }

  const session = await verifySession(token);
  if (!session) {
    return NextResponse.json({ gate: 'unauthenticated' }, { status: 401 });
  }

  if (EXEMPT_ROLES.has(session.role)) {
    const res = NextResponse.json({ gate: 'ok' });
    res.cookies.set(SUB_GATE_COOKIE, 'ok', {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      maxAge: GATE_TTL_SECONDS,
      secure: process.env.NODE_ENV === 'production',
    });
    return res;
  }

  if (!session.restaurantId) {
    return NextResponse.json({ gate: 'ok' });
  }

  try {
    await initDatabase();

    const rows = await db
      .select({ status: subscriptions.status, trialEnd: subscriptions.trialEnd })
      .from(subscriptions)
      .where(eq(subscriptions.restaurantId, session.restaurantId))
      .orderBy(desc(subscriptions.createdAt))
      .limit(1);
    const sub = rows[0];

    let gateValue: 'ok' | 'expired' | 'inactive' = 'ok';
    if (!sub) {
      gateValue = 'inactive';
    } else {
      const isTrialExpired =
        sub.status === 'trial' && sub.trialEnd && new Date(sub.trialEnd) < new Date();
      const isInactive = sub.status === 'inactive' || sub.status === 'cancelled';
      if (isTrialExpired) gateValue = 'expired';
      else if (isInactive) gateValue = 'inactive';
    }

    const res = NextResponse.json({ gate: gateValue });
    res.cookies.set(SUB_GATE_COOKIE, gateValue, {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      maxAge: GATE_TTL_SECONDS,
      secure: process.env.NODE_ENV === 'production',
    });
    return res;
  } catch {
    return NextResponse.json({ gate: 'error' }, { status: 503 });
  }
}
