import { NextResponse, type NextRequest } from 'next/server';
import { COOKIE_NAME } from '@server/auth';
import { evaluateGateForToken } from '@server/services/billing/gate.service';
import { wrapRouteHandler } from '@server/logger/request';

import { childLogger } from '@server/logger';
const log = childLogger('route.auth.gate');

const GATE_TTL_SECONDS = 300;
const SUB_GATE_COOKIE = 'sub_gate';

async function handleGET(request: NextRequest) {
  const token = request.cookies.get(COOKIE_NAME)?.value;

  let gateValue;
  try {
    gateValue = await evaluateGateForToken(token);
  } catch (err) {
    log.error({ err }, 'gate evaluation error');
    return NextResponse.json({ gate: 'error' }, { status: 503 });
  }

  if (gateValue === 'unauthenticated') {
    return NextResponse.json({ gate: 'unauthenticated' }, { status: 401 });
  }

  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;
}

export const GET = wrapRouteHandler((req: Request) => handleGET(req as NextRequest));
