import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { getSubscription } from '@server/services/billing.service';

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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const subscription = await getSubscription(req.session.restaurantId!);

    const res = NextResponse.json({ subscription });

    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      let gateValue: 'ok' | 'expired' | 'inactive' = 'ok';
      if (subscription) {
        const status = subscription.status as string;
        const trialEnd = subscription.trial_end as string | null;
        const isTrialExpired =
          status === 'trial' && trialEnd && new Date(trialEnd) < new Date();
        const isInactive = status === 'inactive' || status === 'cancelled' || status === 'suspended';
        if (isTrialExpired || isInactive) {
          gateValue = isTrialExpired ? 'expired' : 'inactive';
        }
      } else {
        gateValue = 'inactive';
      }
      res.cookies.set(SUB_GATE_COOKIE, gateValue, {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        maxAge: GATE_TTL_SECONDS,
        secure: process.env.NODE_ENV === 'production',
      });
    }

    return res;
  })
);
