import { databaseConfig } from '../../../config/database.js';
import { registerDatabasesFromRuntimeConfig } from '../../../orm/DatabaseRuntimeRegistration.js';
import { SchedulerRuntime } from '../../../scheduler/SchedulerRuntime.js';
const isSchedule = (value) => {
    if (value === undefined || value === null || typeof value !== 'object')
        return false;
    return 'name' in value && typeof value.name === 'string';
};
const loadScheduleModules = async () => {
    const coreSchedules = await import('../../../schedules/index.js');
    let appSchedules = {};
    try {
        appSchedules = (await import('../../../../app/Schedules/index.js'));
    }
    catch {
        appSchedules = {};
    }
    return {
        core: Object.values(coreSchedules).filter(isSchedule),
        app: Object.values(appSchedules).filter(isSchedule),
    };
};
const shutdownCliResources = async () => {
    try {
        const mod = await import('../../../orm/ConnectionManager.js');
        await mod.ConnectionManager.shutdownIfInitialized();
    }
    catch {
        // best-effort
    }
    try {
        const mod = await import('../../../orm/Database.js');
        await mod.resetDatabase();
    }
    catch {
        // best-effort
    }
    try {
        const mod = (await import('../../../tools/queue/LockProvider.js'));
        await mod.closeLockProvider?.();
    }
    catch {
        // best-effort
    }
};
export const ScheduleCliSupport = Object.freeze({
    async registerAll() {
        registerDatabasesFromRuntimeConfig(databaseConfig);
        const modules = await loadScheduleModules();
        SchedulerRuntime.registerMany(modules.core, 'core');
        SchedulerRuntime.registerMany(modules.app, 'app');
    },
    shutdownCliResources,
});
export default ScheduleCliSupport;
