/**
 * Exchange Sankofa API credentials for a GraphQL JWT (server-side only).
 */

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

export async function fetchSankofaApiToken(): Promise<string | undefined> {
  const email = env('PORTAL_SANKOFA_API_EMAIL') || env('PORTAL_LOCAL_LOGIN_EMAIL');
  const password = env('PORTAL_SANKOFA_API_PASSWORD') || env('PORTAL_LOCAL_LOGIN_PASSWORD');
  const base =
    env('SANKOFA_PHOENIX_API_INTERNAL_URL') ||
    env('NEXT_PUBLIC_PHOENIX_API_INTERNAL_URL') ||
    'http://192.168.11.50:8080';

  if (!email || !password) return undefined;

  try {
    const res = await fetch(`${base.replace(/\/$/, '')}/graphql`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        query: `mutation PortalLogin($email: String!, $password: String!) {
          login(email: $email, password: $password) { token }
        }`,
        variables: { email, password },
      }),
      cache: 'no-store',
    });
    if (!res.ok) return undefined;
    const json = (await res.json()) as { data?: { login?: { token?: string } } };
    return json.data?.login?.token;
  } catch {
    return undefined;
  }
}
