// Builder reqs
const { execSync } = require("child_process");

// Prebuild reqs
const { resolve } = require("path");
const { mkdir, cp } = require("fs/promises");
const { existsSync } = require("fs");
const { rimraf } = require("rimraf");

// Load .env file
require('dotenv').config();

async function generateSwagger() {
	// Use the new Zod-based OpenAPI generator
	const { execSync } = require("child_process");
	let serverUrl = '/';

	// Read server URL from environment variable
	if (process.env.BACKEND_URL) {
		serverUrl = process.env.BACKEND_URL;
		console.log(`📍 Using BACKEND_URL from environment: ${serverUrl}`);
	} else {
		console.warn('⚠️ BACKEND_URL not set in environment, using default "/"');
	}

	try {
		const env = { ...process.env, SERVER_URL: serverUrl };
		execSync("pnpm swagger:generate", { stdio: "inherit", cwd: process.cwd(), env });
		console.log('✅ openapi.json generated during build');
	} catch (genErr) {
		console.warn('⚠️ swagger generation failed during build:', genErr && genErr.message ? genErr.message : genErr);
	}
}

console.time("Built time");

(async function main() {
	try {
		const buildPath = resolve(__dirname, "../../dist");
		const templatePath = resolve(buildPath, "templates");

		// Pre-build: Clean and prepare directories
		if (existsSync(buildPath)) {
			await rimraf(buildPath);
		}
		await mkdir(buildPath, { recursive: true });

		// Build with tsc (TypeScript compiler) - handles path aliases natively
		try {
			execSync("npx tsc", { stdio: "inherit", cwd: process.cwd() });
			console.log('✅ TypeScript compilation completed');
		} catch (tscErr) {
			console.error('❌ TypeScript compilation failed:', tscErr);
			throw tscErr;
		}

		// Transform path aliases to relative paths using tsc-alias
		try {
			execSync("npx tsc-alias", { stdio: "inherit", cwd: process.cwd() });
			console.log('✅ Path aliases transformed');
		} catch (aliasErr) {
			console.error('❌ Path alias transformation failed:', aliasErr);
			throw aliasErr;
		}

		// Copy templates
		await cp(resolve(__dirname, "../../src/templates"), templatePath, { recursive: true });

		// Copy lib
		await cp(resolve(__dirname, "../../lib"), resolve(buildPath, "lib"), { recursive: true });

		// Copy necessary files
		// await cp(resolve(__dirname, "../../src/config"), buildConfigPath, { recursive: true });

		// Generate swagger spec into storage during build
		try {
			await generateSwagger();
			console.log('✅ openapi.json generated during build');
		} catch (genErr) {
			console.warn('⚠️ swagger generation failed during build:', genErr && genErr.message ? genErr.message : genErr);
		}

		console.timeEnd("Built time");
		process.exit(0);
	} catch (err) {
		console.error("Build failed:", err);
		process.exit(1);
	}
})();
