import { spawn } from "node:child_process"

const schemaUrl = "https://api.trimgu.ru/api/schema/"
const outputPath = "src/shared/api/__generated__/openapi.types.ts"

const existingHeader = process.env.DOCS_BASIC_AUTH_HEADER
const user = process.env.DOCS_BASIC_AUTH_USER
const password = process.env.DOCS_BASIC_AUTH_PASSWORD

const authHeader =
	existingHeader ??
	(user && password
		? `Basic ${Buffer.from(`${user}:${password}`, "utf8").toString("base64")}`
		: undefined)

if (!authHeader) {
	console.error(
		"Missing docs auth. Set DOCS_BASIC_AUTH_USER and DOCS_BASIC_AUTH_PASSWORD, or DOCS_BASIC_AUTH_HEADER.",
	)
	process.exit(1)
}

const child = spawn(
	"bunx",
	[
		"openapi-typescript",
		schemaUrl,
		"--redocly",
		"redocly.yaml",
		"--output",
		outputPath,
	],
	{
		env: {
			...process.env,
			DOCS_BASIC_AUTH_HEADER: authHeader,
		},
		stdio: "inherit",
	},
)

child.on("exit", (code, signal) => {
	if (signal) {
		console.error(`openapi-typescript stopped by signal ${signal}`)
		process.exit(1)
	}

	process.exit(code ?? 1)
})

child.on("error", (error) => {
	console.error(error.message)
	process.exit(1)
})
