/**
 * Generate TypeScript axios client from openapi.json using @hey-api/openapi-ts.
 * Generates into src/client.
 * Post-processes: injects withCredentials: true and baseURL into the client config.
 */
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

const ROOT = path.join(__dirname, '..');
const CLIENT_DIR = path.join(ROOT, 'src', 'client');
const CLIENT_GEN = path.join(CLIENT_DIR, 'client.gen.ts');

const openapiTsBin = path.join(ROOT, 'node_modules/@hey-api/openapi-ts/bin/run.js');
const openapiJson = path.join(ROOT, 'openapi.json');

console.log('Running @hey-api/openapi-ts...');
try {
    execSync(`node "${openapiTsBin}" -c @hey-api/client-axios -i "${openapiJson}" -o "${CLIENT_DIR}"`, {
        cwd: ROOT,
        stdio: 'inherit',
    });
} catch (e) {
    console.error('Generator exited with code:', e.status);
    process.exit(1);
}

// Post-process: inject withCredentials and baseURL into client config
if (fs.existsSync(CLIENT_GEN)) {
    let content = fs.readFileSync(CLIENT_GEN, 'utf8');

    // Remove unused createConfig import
    content = content.replace(
        "import { type ClientOptions, type Config, createClient, createConfig } from './client';",
        "import { type ClientOptions, type Config, createClient } from './client';"
    );

    // Replace the client creation to include withCredentials and baseURL
    content = content.replace(
        'export const client = createClient(createConfig<ClientOptions2>());',
        `export const createClientConfig = (override?: Config<ClientOptions2>): Config<ClientOptions2> => {
            return {
                withCredentials: true,
                baseURL: import.meta.env.VITE_API_BASE_URL ?? '',
                ...override,
            };
        };
export const client = createClient(createClientConfig());`
    );

    fs.writeFileSync(CLIENT_GEN, content);
    console.log('Updated client.gen.ts with withCredentials and baseURL');
}

console.log('Done.');
