"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertSchedule = insertSchedule;
exports.getDueSchedules = getDueSchedules;
exports.updateScheduleStatus = updateScheduleStatus;
exports.getAllSchedules = getAllSchedules;
exports.getScheduleByUserId = getScheduleByUserId;
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const dbPath = process.env.DB_PATH || "schedules.db";
const db = new better_sqlite3_1.default(dbPath);
db.exec(`
  CREATE TABLE IF NOT EXISTS schedules (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    chain TEXT NOT NULL,
    action TEXT NOT NULL,
    data TEXT NOT NULL,
    time_trigger TEXT NOT NULL,
    onchain_trigger TEXT,
    status TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );
  
  
  CREATE INDEX IF NOT EXISTS idx_user_id ON schedules(user_id);
  CREATE INDEX IF NOT EXISTS idx_time_trigger ON schedules(time_trigger);

`);
process.on("SIGTERM", () => {
    try {
        db.close();
        console.log("Database connection closed gracefully.");
    }
    catch (err) {
        console.error("Error closing database:", err);
    }
    finally {
        process.exit(0);
    }
});
function insertSchedule(schedule) {
    const stmt = db.prepare(`
    INSERT INTO schedules (id, user_id, chain, action, data, time_trigger, onchain_trigger, status, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `);
    stmt.run(schedule.id, schedule.userId, schedule.chain, schedule.action, schedule.data, schedule.timeTrigger, schedule.onChainTrigger ? JSON.stringify(schedule.onChainTrigger) : null, schedule.status, schedule.createdAt, schedule.updatedAt);
}
function getDueSchedules(currentTime) {
    const stmt = db.prepare(`
    SELECT * FROM schedules WHERE status = 'pending' AND time_trigger <= ?
  `);
    const rows = stmt.all(currentTime);
    return rows.map((row) => (Object.assign(Object.assign({}, row), { onChainTrigger: row.onchain_trigger ? JSON.parse(row.onchain_trigger) : undefined })));
}
function updateScheduleStatus(id, status) {
    const stmt = db.prepare(`
    UPDATE schedules SET status = ?, updated_at = ? WHERE id = ?
  `);
    stmt.run(status, new Date().toISOString(), id);
}
function getAllSchedules() {
    const stmt = db.prepare(`SELECT * FROM schedules`);
    const rows = stmt.all();
    return rows.map((row) => (Object.assign(Object.assign({}, row), { onChainTrigger: row.onchain_trigger ? JSON.parse(row.onchain_trigger) : undefined })));
}
function getScheduleByUserId(userID) {
    const stmt = db.prepare(`SELECT * FROM schedules WHERE user_id = ?`);
    const rows = stmt.all(userID);
    return rows.map((row) => (Object.assign(Object.assign({}, row), { onChainTrigger: row.onchain_trigger ? JSON.parse(row.onchain_trigger) : undefined })));
}
