const { queryOne, run } = require('./database');

async function getCachedExtension(extName, id) {
    return queryOne(
        "SELECT metadata FROM extension WHERE ext_name = ? AND id = ?",
        [extName, id]
    );
}

async function cacheExtension(extName, id, title, metadata) {
    return run(
        `
            INSERT INTO extension (ext_name, id, title, metadata, updated_at)
            VALUES (?, ?, ?, ?, ?)
            ON CONFLICT(ext_name, id)
            DO UPDATE SET
                title = excluded.title,
                metadata = excluded.metadata,
                updated_at = ?
        `,
        [extName, id, title, JSON.stringify(metadata), Date.now(), Date.now()]
    );
}

async function getExtensionTitle(extName, id) {
    const sql = "SELECT title FROM extension WHERE ext_name = ? AND id = ?";
    const row = await queryOne(sql, [extName, id], 'anilist');
    return row ? row.title : null;
}

async function deleteExtension(extName) {
    return run(
        "DELETE FROM extension WHERE ext_name = ?",
        [extName]
    );
}

async function getCache(key) {
    return queryOne("SELECT result, created_at, ttl_ms FROM cache WHERE key = ?", [key], "cache");
}

async function setCache(key, result, ttl_ms) {
    return run(
        `
            INSERT INTO cache (key, result, created_at, ttl_ms)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(key)
            DO UPDATE SET result = excluded.result, created_at = excluded.created_at, ttl_ms = excluded.ttl_ms
        `,
        [key, JSON.stringify(result), Date.now(), ttl_ms],
        "cache"
    );
}

module.exports = {
    getCachedExtension,
    cacheExtension,
    getExtensionTitle,
    deleteExtension,
    getCache,
    setCache
};