import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, AuthError } from '@server/errors';
import { verifySession, COOKIE_NAME } from '@server/auth';
import { cookies } from 'next/headers';

const RESTORE_COOKIE = 'admin_restore';
const SESSION_TTL = 7 * 24 * 60 * 60;

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }

    const cookieStore = await cookies();
    const restoreToken = cookieStore.get(RESTORE_COOKIE)?.value;
    if (!restoreToken) {
      throw new AuthError('No active impersonation session found');
    }

    const restored = await verifySession(restoreToken);
    if (!restored) {
      throw new AuthError('Restore session is invalid or expired');
    }

    const body = await req.json().catch(() => ({})) as { restaurantId?: string };
    const restaurantId = body.restaurantId ?? cookieStore.get('impersonating_restaurant_id')?.value ?? null;

    const secure = process.env.NODE_ENV === 'production';
    const res = NextResponse.json({ ok: true, restaurantId });

    res.cookies.set(COOKIE_NAME, restoreToken, {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      maxAge: SESSION_TTL,
      secure,
    });

    res.cookies.set(RESTORE_COOKIE, '', {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      maxAge: 0,
      secure,
    });

    res.cookies.set('impersonating_name', '', {
      httpOnly: false,
      sameSite: 'lax',
      path: '/',
      maxAge: 0,
      secure,
    });

    res.cookies.set('impersonating_restaurant_id', '', {
      httpOnly: false,
      sameSite: 'lax',
      path: '/',
      maxAge: 0,
      secure,
    });

    return res;
  })
);
