"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TestService = void 0;
const logger_1 = require("../utils/logger");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const path_1 = require("../utils/path");
const child_process_1 = require("child_process");
const license_file_service_1 = require("./license-file.service");
/**
 * TestService handles running automated tests for the io.Connect Desktop application.
 *
 * This service:
 * - Locates the tests directory in the project
 * - Ensures node_modules are installed in the tests directory
 * - Sets the BINARY_PATH environment variable to point to the built executable
 * - Runs the test script defined in the tests package.json
 */
class TestService {
    logger = logger_1.Logger.getInstance("test.service");
    /**
     * Run tests for the io.Connect Desktop application
     */
    async runTests() {
        this.logger.info("Starting test execution...");
        // Find tests directory
        const testsDir = path_1.PathUtils.getTestsDir();
        if (!fs.existsSync(testsDir)) {
            throw new Error(`Tests directory not found. Expected '${testsDir}' folder in project root.`);
        }
        this.logger.debug(`Tests directory: ${testsDir}`);
        // Check if node_modules exists, if not run npm install
        await this.ensureNodeModulesInstalled(testsDir);
        // Get the binary path based on platform
        const binaryPath = path_1.PathUtils.getIOCDExePath();
        this.logger.info(`Binary path: ${binaryPath}`);
        // Verify binary exists
        if (!fs.existsSync(binaryPath)) {
            throw new Error(`Binary not found at ${binaryPath}. Please run 'iocd dev' first to create the executable.`);
        }
        // copy license file to binary directory if it exists
        await license_file_service_1.LicenseFileService.copyLicenseFile(true);
        // Run the test script
        await this.runTestScript(testsDir, binaryPath);
        // remove license file after tests (as tests ignore the copy setting)
        await license_file_service_1.LicenseFileService.removeLicenseFile();
    }
    /**
     * Ensure node_modules are installed in the tests directory
     */
    async ensureNodeModulesInstalled(testsDir) {
        const nodeModulesPath = path.join(testsDir, "node_modules");
        const packageJsonPath = path.join(testsDir, "package.json");
        if (!fs.existsSync(packageJsonPath)) {
            throw new Error(`No package.json found in tests directory: ${testsDir}`);
        }
        if (fs.existsSync(nodeModulesPath)) {
            this.logger.debug("node_modules already exists in tests directory");
            return;
        }
        this.logger.info("Installing dependencies in tests directory...");
        await this.runNpmInstall(testsDir);
        this.logger.info("Dependencies installed successfully");
    }
    /**
     * Run npm install in the specified directory
     */
    async runNpmInstall(cwd) {
        return new Promise((resolve, reject) => {
            const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
            const child = (0, child_process_1.spawn)(npmCommand, ["install"], {
                cwd,
                stdio: "inherit",
                shell: true,
            });
            child.on("close", code => {
                if (code === 0) {
                    resolve();
                }
                else {
                    reject(new Error(`npm install failed with code ${code}`));
                }
            });
            child.on("error", err => {
                reject(err);
            });
        });
    }
    /**
     * Run the test script in the tests directory
     */
    async runTestScript(testsDir, binaryPath) {
        this.logger.info("Running tests...");
        return new Promise((resolve, reject) => {
            const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
            const child = (0, child_process_1.spawn)(npmCommand, ["test"], {
                cwd: testsDir,
                stdio: "inherit",
                shell: true,
                env: {
                    ...process.env,
                    BINARY_PATH: binaryPath,
                },
            });
            child.on("close", code => {
                if (code === 0) {
                    this.logger.info("Tests completed successfully");
                    resolve();
                }
                else {
                    reject(new Error(`Tests failed with code ${code}`));
                }
            });
            child.on("error", err => {
                reject(err);
            });
        });
    }
}
exports.TestService = TestService;
//# sourceMappingURL=test.service.js.map