#!/usr/bin/env node
/**
 * Post-process script for openapi-ts generation.
 * Patches client.gen.ts to use request-scoped clients from server storage,
 * preventing cross-request cookie/origin leakage during SSR.
 */

/* eslint-disable no-console */

import { writeFileSync } from "node:fs";
import { resolve } from "node:path";

const CLIENT_GEN_PATH = resolve(process.cwd(), "app/client/api-client/client.gen.ts");

const PATCHED_CONTENT = `// @ts-nocheck
// This file is auto-generated by @hey-api/openapi-ts
import { type ClientOptions, type Config, createClient, createConfig } from "./client";
import type { ClientOptions as ClientOptions2 } from "./types.gen";
import { getRequestClient } from "../../lib/request-client";

export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (
	override?: Config<ClientOptions & T>,
) => Config<Required<ClientOptions> & T>;

const fallbackClient = createClient(createConfig<ClientOptions2>({ baseUrl: "http://localhost:4096" }));

/**
 * Proxy client that automatically uses the per-request client from request-scoped server storage.
 * Falls back to a default client if no request context is available.
 */
export const client = new Proxy(fallbackClient, {
	get(target, prop, receiver) {
		try {
			const requestClient = getRequestClient();
			return Reflect.get(requestClient, prop, receiver);
		} catch {
			// No request context available, use fallback
			return Reflect.get(target, prop, receiver);
		}
	},
});
`;

try {
	writeFileSync(CLIENT_GEN_PATH, PATCHED_CONTENT);
	console.log("✓ Patched client.gen.ts with request-scoped client support");
} catch (error) {
	console.error("✗ Failed to patch client.gen.ts:", error instanceof Error ? error.message : String(error));
	process.exit(1);
}
