import { getServerSession } from 'next-auth';

import { authOptions } from '@/lib/auth';
import { sessionHasItOpsRole } from '@/lib/it-ops-roles';

export type ItSession = {
  roles?: string[];
} | null;

export async function requireItOpsSession(): Promise<ItSession> {
  const session = (await getServerSession(authOptions)) as ItSession;
  if (!session || !sessionHasItOpsRole(session.roles)) {
    return null;
  }
  return session;
}

function readEnv(name: string): string | undefined {
  const v = process.env[name];
  return typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined;
}

export function itReadApiBaseUrl(): string | undefined {
  return readEnv('IT_READ_API_URL');
}

export function itReadApiKey(): string | undefined {
  return readEnv('IT_READ_API_KEY');
}
