/**
 * Server-side billing proxy utilities for Next.js Route Handlers.
 *
 * Provides a typed proxy to the Django billing API, with optional
 * camelCase-to-snake_case response normalization (Django's DRF camel-case
 * middleware returns camelCase; some billing consumers expect snake_case).
 *
 * Import via: import { proxyBillingRequest, fetchDjangoServiceToken, camelToSnake } from '@startsimpli/billing/server'
 */

import { NextResponse } from 'next/server';

export interface DjangoServiceTokenOptions {
  /** Django base URL. Defaults to INTERNAL_API_URL ?? NEXT_PUBLIC_API_URL env vars. */
  apiUrl?: string;
  /** Shared service key. Defaults to INTERNAL_SERVICE_KEY env var. */
  serviceKey?: string;
}

/**
 * Exchange the shared INTERNAL_SERVICE_KEY for a Django JWT for the given user.
 *
 * Must only be called server-side (Route Handlers, Server Actions).
 * Never expose the service key or the returned JWT to the browser.
 *
 * Django creates the user if they don't exist and ensures they have a Team,
 * so billing endpoints (which require team membership) work immediately.
 *
 * Prefers INTERNAL_API_URL over NEXT_PUBLIC_API_URL for server-to-server
 * calls — set INTERNAL_API_URL to the Docker service name in production
 * (e.g. http://django:8000) to avoid routing through the public load balancer.
 */
export async function fetchDjangoServiceToken(
  email: string,
  name?: string | null,
  opts?: DjangoServiceTokenOptions,
): Promise<string | undefined> {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const env = (typeof process !== 'undefined' ? process.env : {}) as Record<string, string | undefined>;
  const apiUrl =
    opts?.apiUrl ??
    env['INTERNAL_API_URL'] ??
    env['NEXT_PUBLIC_API_URL'] ??
    '';
  const serviceKey = opts?.serviceKey ?? env['INTERNAL_SERVICE_KEY'] ?? '';

  if (!serviceKey) {
    console.error('[billing] INTERNAL_SERVICE_KEY is not set — billing auth will fail');
    return undefined;
  }

  try {
    const response = await fetch(`${apiUrl}/api/v1/auth/service-token/`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, name: name ?? '', service_key: serviceKey }),
      cache: 'no-store',
    });
    if (response.ok) {
      const data = await response.json() as { access?: string };
      return data.access;
    }
    const body = await response.text();
    console.error('[billing] service-token failed:', response.status, body);
    return undefined;
  } catch (err) {
    console.error('[billing] service-token request threw:', err);
    return undefined;
  }
}

/**
 * Recursively converts camelCase object keys to snake_case.
 * Useful when Django's camel-case middleware returns camelCase field names
 * but downstream consumers expect snake_case.
 */
export function camelToSnake(obj: unknown): unknown {
  if (Array.isArray(obj)) return obj.map(camelToSnake);
  if (obj !== null && typeof obj === 'object') {
    return Object.fromEntries(
      Object.entries(obj as Record<string, unknown>).map(([k, v]) => [
        k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`),
        camelToSnake(v),
      ])
    );
  }
  return obj;
}

/**
 * Recursively converts snake_case object keys to camelCase.
 * Used for Django endpoints that bypass the camel-case middleware
 * (e.g. public product endpoints) so consumers always receive camelCase.
 */
export function snakeToCamel(obj: unknown): unknown {
  if (Array.isArray(obj)) return obj.map(snakeToCamel);
  if (obj !== null && typeof obj === 'object') {
    return Object.fromEntries(
      Object.entries(obj as Record<string, unknown>).map(([k, v]) => [
        k.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase()),
        snakeToCamel(v),
      ])
    );
  }
  return obj;
}

export interface BillingProxyOptions {
  method?: string;
  body?: unknown;
  /** If true, apply camelToSnake transform to the response body */
  normalize?: boolean;
  /** If true, apply snakeToCamel transform to the response body */
  fromSnake?: boolean;
  /** If true, skip Authorization header even when accessToken is provided */
  public?: boolean;
}

/**
 * Proxy a request to the Django billing API from a Next.js Route Handler.
 *
 * @param apiBaseUrl  - Django API base URL (e.g. process.env.NEXT_PUBLIC_API_URL)
 * @param path        - Billing API path (e.g. '/api/v1/billing/subscription/current/')
 * @param accessToken - JWT access token from the current session (or undefined)
 * @param options     - method, body, normalize, public
 */
export async function proxyBillingRequest(
  apiBaseUrl: string,
  path: string,
  accessToken: string | undefined,
  options: BillingProxyOptions = {}
): Promise<NextResponse> {
  const { method = 'GET', body, normalize = false, fromSnake = false } = options;
  const url = `${apiBaseUrl}${path}`;

  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  if (!options.public && accessToken) {
    headers['Authorization'] = `Bearer ${accessToken}`;
  }

  try {
    const response = await fetch(url, {
      method,
      headers,
      body: body !== undefined ? JSON.stringify(body) : undefined,
      cache: 'no-store',
    });

    if (!response.ok) {
      const errorData = await response.text();
      return NextResponse.json(
        { error: 'Billing API error', status: response.status, details: errorData },
        { status: response.status }
      );
    }

    const data = await response.json();
    const transformed = normalize ? camelToSnake(data) : fromSnake ? snakeToCamel(data) : data;
    return NextResponse.json(transformed);
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Internal server error',
        details: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    );
  }
}
