"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MaintenanceHealthRepository = void 0;
const common_1 = require("@nestjs/common");
const node_child_process_1 = require("node:child_process");
const node_path_1 = require("node:path");
const constants_1 = require("../constants");
let MaintenanceHealthRepository = class MaintenanceHealthRepository {
    checkApiHealth() {
        return new Promise((resolve, reject) => {
            const basePath = (0, node_path_1.dirname)(__filename);
            const workerFile = (0, node_path_1.join)(basePath, '..', 'workers', `api.js`);
            const worker = (0, node_child_process_1.fork)(workerFile, [], {
                execArgv: process.execArgv.filter((arg) => !arg.startsWith('--inspect')),
                env: {
                    ...process.env,
                    IMMICH_HOST: '127.0.0.1',
                    IMMICH_PORT: '33001',
                },
                stdio: ['ignore', 'pipe', 'ignore', 'ipc'],
            });
            let output = '';
            worker.stdout?.on('data', (data) => {
                if (worker.exitCode !== null) {
                    return;
                }
                output += data;
                if (output.includes(constants_1.IMMICH_SERVER_START)) {
                    resolve();
                    worker.kill('SIGTERM');
                }
            });
            worker.on('exit', (code, signal) => reject(new Error(`Server health check failed, server exited with ${signal ?? code}`)));
            worker.on('error', (error) => reject(new Error(`Server health check failed, process threw: ${error}`)));
            setTimeout(() => {
                if (worker.exitCode === null) {
                    reject(new Error('Server health check failed, took too long to start.'));
                    worker.kill('SIGTERM');
                }
            }, 180_000);
        });
    }
};
exports.MaintenanceHealthRepository = MaintenanceHealthRepository;
exports.MaintenanceHealthRepository = MaintenanceHealthRepository = __decorate([
    (0, common_1.Injectable)()
], MaintenanceHealthRepository);
//# sourceMappingURL=maintenance-health.repository.js.map