import { cookies } from 'next/headers';
import { authCookieName, refreshCookieName } from './auth';
import { SERVER_API_URL } from './server-api';

const secureCookies = process.env.NODE_ENV === 'production';

type RefreshPayload = {
  access_token: string;
  refresh_token: string;
  access_token_max_age_seconds?: number;
  refresh_token_max_age_seconds?: number;
};

export async function getProxyAccessToken() {
  const cookieStore = await cookies();
  const accessToken = cookieStore.get(authCookieName)?.value;
  if (accessToken) {
    return accessToken;
  }

  const refreshToken = cookieStore.get(refreshCookieName)?.value;
  if (!refreshToken) {
    return null;
  }

  const response = await fetch(`${SERVER_API_URL}/auth/refresh`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ refreshToken }),
    cache: 'no-store',
  });

  if (!response.ok) {
    return null;
  }

  const payload = (await response.json()) as RefreshPayload;
  if (!payload.access_token || !payload.refresh_token) {
    return null;
  }

  cookieStore.set(authCookieName, payload.access_token, {
    httpOnly: true,
    sameSite: 'lax',
    secure: secureCookies,
    path: '/',
    maxAge: payload.access_token_max_age_seconds || 60 * 60 * 24,
  });
  cookieStore.set(refreshCookieName, payload.refresh_token, {
    httpOnly: true,
    sameSite: 'lax',
    secure: secureCookies,
    path: '/',
    maxAge: payload.refresh_token_max_age_seconds || 60 * 60 * 24 * 30,
  });

  return payload.access_token;
}
