import { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';
import { workUnitAsyncStorage } from 'next/dist/server/app-render/work-unit-async-storage.external';

import { getCurrentLocale } from '@/utils/locale';

export class OpenApiHttpError extends Error {
  constructor(
    message: string,
    public readonly status: number,
    public readonly headers: Headers
  ) {
    super(message);
    this.name = 'OpenApiHttpError';
  }
}

type OpenApiRequestOptions = RequestInit & {
  next?: {
    revalidate?: number | false;
    tags?: string[];
  };
};

function getTestApiBasicAuthHeaders(): Record<string, string> {
  if (process.env.NEXT_PUBLIC_ENV !== 'test') return {};

  const username = process.env.BASIC_AUTH_USER;
  const password = process.env.BASIC_AUTH_PASS;
  if (!username || !password) return {};

  return {
    Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
  };
}

function getAcceptLanguageHeader(locale: string): string {
  return locale === 'en' ? 'en-US,en;q=0.9,hu;q=0.8' : 'hu-HU,hu;q=0.9,en-US;q=0.8,en;q=0.7';
}

/*
 * CSRF (Spring cookie repository, double submit): the backend rejects state-changing requests
 * unless the X-XSRF-TOKEN header matches the XSRF-TOKEN cookie sent along. Server-side calls
 * carry no browser cookies, so there is nothing to forge and a fixed pair passes the check.
 * It is fixed on purpose: request headers are part of Next's fetch-cache key, so a token fetched
 * from /api/auth/csrf would change the key per process and miss the shared cache.
 */
const CSRF_COOKIE_NAME = 'XSRF-TOKEN';
const CSRF_HEADER_NAME = 'X-XSRF-TOKEN';
const SERVER_CSRF_TOKEN = 'azopus-next-server';
const CSRF_SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);

function applyCsrfHeaders(headers: Headers, method: string | undefined) {
  if (CSRF_SAFE_METHODS.has((method ?? 'GET').toUpperCase())) return;

  const csrfCookie = `${CSRF_COOKIE_NAME}=${SERVER_CSRF_TOKEN}`;
  const cookie = headers.get('cookie');
  // Spring reads the first XSRF-TOKEN cookie, so this one goes before any forwarded cookies.
  headers.set('cookie', cookie ? `${csrfCookie}; ${cookie}` : csrfCookie);
  headers.set(CSRF_HEADER_NAME, SERVER_CSRF_TOKEN);
}

// Java API data changes rarely and editors refresh a page right after editing via the
// admin toolbar, so responses are cached for a day unless a call overrides it.
const DEFAULT_REVALIDATE_SECONDS = 86_400;

/** For time-sensitive data (programs, news) that should refresh within minutes. */
export const TIMELY_REVALIDATE_SECONDS = 900;

async function createOpenApiRequestOptions(
  options: OpenApiRequestOptions = {}
): Promise<OpenApiRequestOptions> {
  const locale = await getCurrentLocale();
  const headers = new Headers({
    ...getTestApiBasicAuthHeaders(),
    'Accept-Language': getAcceptLanguageHeader(locale),
  });
  new Headers(options.headers).forEach((value, name) => headers.set(name, value));
  applyCsrfHeaders(headers, options.method);
  return {
    ...options,
    headers,
    next:
      options.next ??
      (options.cache === 'no-store' ? undefined : { revalidate: DEFAULT_REVALIDATE_SECONDS }),
  };
}

export type ApiCallLogEntry = {
  at: string;
  method: string;
  path: string;
  body: string | null;
  outcome: string;
  durationMs: number;
  cache: string;
  source: string;
  /** Page or route path being rendered when the call started (e.g. `/hu/alkoto/AL1`). */
  page: string | null;
  /** Route file pattern of that render (e.g. `/[locale]/alkoto/[id]/[section]`). */
  route: string | null;
  trigger: ApiCallTrigger;
};

/**
 * Why the server was rendering: `build` = next build, `isr` = static page generated on
 * first visit or regenerated in the background, `revalidate` = on-demand (admin refresh),
 * `page-load` / `navigation` / `prefetch` = request-time render of a dynamic page,
 * `api` = route handler.
 */
export type ApiCallTrigger =
  | 'build'
  | 'isr'
  | 'revalidate'
  | 'page-load'
  | 'navigation'
  | 'prefetch'
  | 'api'
  | 'other';

const API_CALL_LOG_LIMIT = 300;

// Shared via globalThis so route handlers and server components read the same buffer.
const apiCallLog: ApiCallLogEntry[] = ((
  globalThis as { __azopusApiCallLog?: ApiCallLogEntry[] }
).__azopusApiCallLog ??= []);

export function isApiDebugEnabled(): boolean {
  return process.env.API_DEBUG === '1' && process.env.NEXT_PUBLIC_ENV !== 'production';
}

/** Most recent Java API calls of this server process, newest first. */
export function getRecentApiCalls(): ApiCallLogEntry[] {
  return [...apiCallLog].reverse();
}

export function clearRecentApiCalls() {
  apiCallLog.length = 0;
}

// Debug only: reads Next's render context (the shared `.external` stores) instead of
// `headers()`, which would opt statically rendered pages into dynamic rendering.
function getRenderContext(): Pick<ApiCallLogEntry, 'page' | 'route' | 'trigger'> {
  try {
    const work = workAsyncStorage.getStore();
    const unit = workUnitAsyncStorage.getStore();
    const route = work?.route ?? null;
    const pathTag = unit?.implicitTags?.tags
      .map((tag) => tag.replace(/^_N_T_/, ''))
      .find((tag) => !tag.includes('[') && !/\/(layout|page|route)$/.test(tag));
    // Request-time renders and route handlers know the full URL, query included.
    const page =
      unit?.type === 'request'
        ? decodeURIComponent(unit.url.pathname + unit.url.search)
        : (pathTag ?? null);
    let trigger: ApiCallTrigger = 'other';

    if (route?.startsWith('/api/')) trigger = 'api';
    else if (work?.isBuildTimePrerendering) trigger = 'build';
    else if (unit?.type === 'request') {
      trigger = unit.headers.get('next-router-prefetch')
        ? 'prefetch'
        : unit.headers.get('rsc')
          ? 'navigation'
          : 'page-load';
    } else if (unit?.type.startsWith('prerender')) {
      trigger = work?.isOnDemandRevalidate ? 'revalidate' : 'isr';
    }

    return { page, route, trigger };
  } catch {
    return { page: null, route: null, trigger: 'other' };
  }
}

const SEEN_RESPONSE_LIMIT = 1000;

// Last Java `Date` header seen per request, to spot replays of a response fetched moments ago.
const seenResponseDates: Map<string, string> = ((
  globalThis as { __azopusSeenResponseDates?: Map<string, string> }
).__azopusSeenResponseDates ??= new Map());

// Next's fetch cache replays the stored upstream headers, so the Java `Date` header
// tells whether this response was just fetched or served from the cache (and how old).
function getResponseSource(
  requestKey: string,
  response: Response | null,
  options: OpenApiRequestOptions
): string {
  if (!response) return '-';
  const dateHeader = response.headers.get('date');
  const date = Date.parse(dateHeader ?? '');
  if (!dateHeader || Number.isNaN(date)) return '?';

  const isReplay = seenResponseDates.get(requestKey) === dateHeader;
  seenResponseDates.delete(requestKey);
  seenResponseDates.set(requestKey, dateHeader);
  if (seenResponseDates.size > SEEN_RESPONSE_LIMIT) {
    seenResponseDates.delete(seenResponseDates.keys().next().value!);
  }

  const ageSeconds = Math.round((Date.now() - date) / 1000);
  if (ageSeconds < 2 && !isReplay) return 'java';
  const revalidate = options.next?.revalidate;
  return typeof revalidate === 'number' && ageSeconds > revalidate
    ? `stale cache ${ageSeconds}s`
    : `cache ${ageSeconds}s`;
}

// Request bodies that carry credentials (the login sends the password in its JSON body).
const SECRET_BODY_PATHS = ['/api/auth/login'];

// In-memory trace of openApiFetch requests for the /openapi-fetch page, enabled with API_DEBUG=1
// outside production. Headers are never stored: they carry Basic auth, Bearer tokens and cookies;
// neither are the bodies of the paths above.
function logApiCall(
  url: string,
  options: OpenApiRequestOptions,
  response: Response | null,
  startedAt: number
) {
  if (!isApiDebugEnabled()) return;

  const { pathname, search } = new URL(url);
  const secretBody = SECRET_BODY_PATHS.some((path) => pathname.endsWith(path));
  const body =
    typeof options.body === 'string'
      ? secretBody
        ? '[redacted]'
        : options.body.slice(0, 1000)
      : null;
  const entry: ApiCallLogEntry = {
    at: new Date().toISOString(),
    method: options.method ?? 'GET',
    path: decodeURIComponent(pathname + search),
    body,
    outcome: response ? String(response.status) : 'network error',
    durationMs: Math.round(performance.now() - startedAt),
    cache:
      options.cache === 'no-store' ? 'no-store' : `revalidate=${options.next?.revalidate ?? '-'}`,
    source: getResponseSource(
      `${options.method ?? 'GET'} ${url} ${secretBody ? '' : (options.body ?? '')}`,
      response,
      options
    ),
    ...getRenderContext(),
  };

  apiCallLog.push(entry);
  if (apiCallLog.length > API_CALL_LOG_LIMIT) apiCallLog.shift();
}

/**
 * Shared Orval mutator for the new API. It keeps server-side OpenAPI requests
 * consistent with browser requests: language headers, test Apache Basic auth and
 * Next fetch-cache settings are applied in one place.
 */
export async function openApiFetch<T>(url: string, options: RequestInit): Promise<T> {
  if (!process.env.NEXT_PUBLIC_NEW_API_URL) {
    throw new Error('NEXT_PUBLIC_NEW_API_URL is not configured.');
  }

  const requestOptions = await createOpenApiRequestOptions(options);
  const startedAt = performance.now();
  let response: Response;
  try {
    response = await fetch(url, {
      credentials: 'include',
      ...requestOptions,
    });
  } catch (error) {
    logApiCall(url, requestOptions, null, startedAt);
    throw error;
  }
  logApiCall(url, requestOptions, response, startedAt);
  const responseText = [204, 205, 304].includes(response.status) ? '' : await response.text();

  if (!response.ok) {
    const contentType = response.headers.get('content-type') ?? 'unknown content type';
    const responseSummary = responseText
      ? ` ${responseText.replace(/\s+/g, ' ').slice(0, 200)}`
      : '';
    throw new OpenApiHttpError(
      `New API request failed with HTTP ${response.status} (${contentType}).${responseSummary}`,
      response.status,
      response.headers
    );
  }

  let data: unknown = undefined;
  if (responseText) {
    try {
      data = JSON.parse(responseText);
    } catch {
      data = responseText;
    }
  }

  return { data, status: response.status, headers: response.headers } as T;
}
