import { NextResponse } from 'next/server';
import { validateStaffSession, type StaffUser } from '../staff-session';

type GuardOptions = {
  requireAdmin?: boolean;
  routeName?: string;
};

/**
 * Shared guard for /api/dev/* and /api/debug/* endpoints.
 * Ensures the request is not served in production and that a staff session exists.
 */
export async function enforceNonProdStaffAccess(
  options: GuardOptions = {}
): Promise<{ response: NextResponse | null; staffSession: StaffUser | null }> {
  const { requireAdmin = false, routeName = 'restricted endpoint' } = options;

  if (process.env.NODE_ENV === 'production') {
    return { response: NextResponse.json({ error: 'Not available' }, { status: 404 }), staffSession: null };
  }

  const staffSession = await validateStaffSession();
  const staffRole = staffSession?.role?.toUpperCase();

  if (!staffSession) {
    return {
      response: NextResponse.json(
        { error: `Staff authentication required for ${routeName}` },
        { status: 401 }
      ),
      staffSession: null,
    };
  }

  if (requireAdmin && staffRole !== 'ADMIN' && staffRole !== 'SUPER_ADMIN') {
    return {
      response: NextResponse.json(
        { error: 'Admin staff access required' },
        { status: 403 }
      ),
      staffSession: null,
    };
  }

  return { response: null, staffSession };
}
