import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { getDefaultConfigDir } from "../config.js";
import { openDatabase } from "../node-compat/sqlite.js";
const TTL_DAYS = 7;
const TTL_MS = TTL_DAYS * 24 * 60 * 60 * 1000;
let db = null;
async function getDatabase() {
    if (db) {
        return db;
    }
    const configDir = getDefaultConfigDir();
    await mkdir(configDir, { recursive: true });
    const dbPath = join(configDir, 'resource.db');
    db = await openDatabase(dbPath);
    db.exec('PRAGMA journal_mode = WAL');
    db.exec('PRAGMA busy_timeout = 5000');
    db.exec('PRAGMA synchronous = NORMAL');
    db.exec(`
		CREATE TABLE IF NOT EXISTS resource_region_cache (
			resource_type TEXT NOT NULL,
			profile TEXT NOT NULL,
			id TEXT NOT NULL,
			region TEXT NOT NULL,
			org_id TEXT,
			project_id TEXT,
			last_updated INTEGER NOT NULL,
			PRIMARY KEY (resource_type, profile, id)
		)
	`);
    db.exec(`
		CREATE INDEX IF NOT EXISTS idx_last_updated 
		ON resource_region_cache(last_updated)
	`);
    // Migration: Add project_id column if it doesn't exist (for existing databases)
    try {
        db.exec('ALTER TABLE resource_region_cache ADD COLUMN project_id TEXT');
    }
    catch {
        // Column already exists, ignore the error
    }
    return db;
}
function pruneOldEntries(database) {
    const cutoff = Date.now() - TTL_MS;
    database.prepare('DELETE FROM resource_region_cache WHERE last_updated < ?').run(cutoff);
}
/**
 * Get the cached info (region and orgId) for a resource.
 * Returns null if not found or expired.
 */
export async function getResourceInfo(type, profile, id) {
    try {
        const database = await getDatabase();
        const cutoff = Date.now() - TTL_MS;
        const row = database
            .prepare('SELECT region, org_id, project_id, last_updated FROM resource_region_cache WHERE resource_type = ? AND profile = ? AND id = ?')
            .get(type, profile, id);
        if (!row) {
            return null;
        }
        // Check if entry is expired
        if (row.last_updated < cutoff) {
            // Remove stale entry
            database
                .prepare('DELETE FROM resource_region_cache WHERE resource_type = ? AND profile = ? AND id = ?')
                .run(type, profile, id);
            return null;
        }
        return {
            region: row.region,
            orgId: row.org_id ?? undefined,
            projectId: row.project_id ?? undefined,
        };
    }
    catch {
        return null;
    }
}
/**
 * Set the cached info for a resource.
 * Uses INSERT OR REPLACE to upsert.
 */
export async function setResourceInfo(type, profile, id, region, orgId, projectId) {
    try {
        const database = await getDatabase();
        pruneOldEntries(database);
        database
            .prepare(`INSERT OR REPLACE INTO resource_region_cache 
			 (resource_type, profile, id, region, org_id, project_id, last_updated)
			 VALUES (?, ?, ?, ?, ?, ?, ?)`)
            .run(type, profile, id, region, orgId ?? null, projectId ?? null, Date.now());
    }
    catch {
        // Non-critical cache failure should never block the CLI.
    }
}
/**
 * Delete the cached info for a resource.
 * Called when a resource is deleted.
 */
export async function deleteResourceRegion(type, profile, id) {
    try {
        const database = await getDatabase();
        database
            .prepare('DELETE FROM resource_region_cache WHERE resource_type = ? AND profile = ? AND id = ?')
            .run(type, profile, id);
    }
    catch {
        // Non-critical cache failure should never block the CLI.
    }
}
/**
 * Clear all cached entries for a specific profile.
 * Useful when switching profiles or logging out.
 */
export async function clearProfileCache(profile) {
    try {
        const database = await getDatabase();
        database.prepare('DELETE FROM resource_region_cache WHERE profile = ?').run(profile);
    }
    catch {
        // Non-critical cache failure should never block the CLI.
    }
}
/**
 * Close the database connection.
 * Should be called on CLI exit for clean shutdown.
 */
export function closeDatabase() {
    if (db) {
        db.close();
        db = null;
    }
}
//# sourceMappingURL=resource-region.js.map