import { loadLinearConfig } from '../linear/config.js';
import { loadJiraConfig } from '../jira/config.js';
const SETTINGS_TABLE = 'workspace_settings';
const ACTIVE_SOURCE_KEY = 'work.active_source';
export const WORK_SOURCE_PROVIDERS = ['pmo', 'linear', 'jira', 'asana', 'monday'];
function getSetting(db, key) {
    const row = db
        .prepare(`SELECT value FROM ${SETTINGS_TABLE} WHERE key = ?`)
        .get(key);
    return row?.value ?? null;
}
function setSetting(db, key, value) {
    db.prepare(`
    INSERT INTO ${SETTINGS_TABLE} (key, value)
    VALUES (?, ?)
    ON CONFLICT(key) DO UPDATE SET value = excluded.value
  `).run(key, value);
}
function deleteSetting(db, key) {
    db.prepare(`DELETE FROM ${SETTINGS_TABLE} WHERE key = ?`).run(key);
}
export function isWorkSourceProvider(value) {
    return WORK_SOURCE_PROVIDERS.includes(value);
}
export function parseWorkSourceRef(input) {
    const raw = input.trim();
    if (!raw) {
        throw new Error('Work source cannot be empty.');
    }
    const separatorIndex = raw.indexOf(':');
    const providerText = separatorIndex === -1 ? raw : raw.slice(0, separatorIndex);
    const provider = providerText.toLowerCase();
    if (!isWorkSourceProvider(provider)) {
        throw new Error(`Unsupported work source provider "${providerText}". Allowed: ${WORK_SOURCE_PROVIDERS.join(', ')}`);
    }
    const rawContext = separatorIndex === -1 ? '' : raw.slice(separatorIndex + 1).trim();
    const context = rawContext.length > 0 ? rawContext : undefined;
    return { provider, context };
}
export function formatWorkSourceRef(source) {
    return source.context ? `${source.provider}:${source.context}` : source.provider;
}
export function saveActiveWorkSource(db, source) {
    setSetting(db, ACTIVE_SOURCE_KEY, formatWorkSourceRef(source));
}
export function clearActiveWorkSource(db) {
    deleteSetting(db, ACTIVE_SOURCE_KEY);
}
export function loadActiveWorkSource(db) {
    const raw = getSetting(db, ACTIVE_SOURCE_KEY);
    if (!raw)
        return null;
    try {
        return parseWorkSourceRef(raw);
    }
    catch {
        return null;
    }
}
export function getRegisteredWorkSources(db) {
    const providers = new Map();
    providers.set('pmo', { provider: 'pmo' });
    const linearConfig = loadLinearConfig(db);
    if (linearConfig) {
        providers.set('linear', {
            provider: 'linear',
            context: linearConfig.defaultTeamKey ?? undefined,
        });
    }
    const jiraConfig = loadJiraConfig(db);
    if (jiraConfig) {
        providers.set('jira', {
            provider: 'jira',
            context: jiraConfig.projectKey ?? undefined,
        });
    }
    return Array.from(providers.values());
}
//# sourceMappingURL=config.js.map