import { createRequire } from 'node:module';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFile, writeFile } from 'node:fs/promises';

const require = createRequire(import.meta.url);
const { generate } = require('openapi-typescript-codegen');

const rootDir = dirname(fileURLToPath(import.meta.url));
const input = resolve(rootDir, 'openapi.json');
const output = resolve(rootDir, 'src/client');

await generate({
  input,
  output,
  httpClient: 'axios',
  useOptions: true,
  useUnionTypes: true,
  exportCore: true,
  exportServices: true,
  exportModels: true,
  exportSchemas: true,
  indent: 'tab',
});

console.log(`Generated OpenAPI client: ${output}`);

const openApiPath = resolve(output, 'core/OpenAPI.ts');
const openApiContent = await readFile(openApiPath, 'utf8');
const updatedOpenApiContent = openApiContent.replace(
  'WITH_CREDENTIALS: false,',
  'WITH_CREDENTIALS: true,',
);
await writeFile(openApiPath, updatedOpenApiContent);
console.log(`Updated OpenAPI.ts`);