const crypto = require("node:crypto"); const { getDb } = require("../config/db"); const { nowIso } = require("../utils/time"); function createJob(input) { const db = getDb(); const id = crypto.randomUUID(); const now = nowIso(); const job = { id, type: input.type, chatId: String(input.chatId), userId: String(input.userId), source: input.source, sourceUrl: input.sourceUrl || null, inputPath: input.inputPath || null, outputPaths: [], mode: input.mode || "auto", status: "queued", progress: 0, stage: "queued", attempts: 0, maxAttempts: input.maxAttempts || 3, error: null, checksum: null, telegramMessageId: input.telegramMessageId || null, metadata: input.metadata || {} }; db.prepare(` INSERT INTO jobs (id, type, chat_id, user_id, source, source_url, input_path, output_paths, mode, status, progress, stage, attempts, max_attempts, error, checksum, telegram_message_id, metadata, created_at, updated_at) VALUES (@id, @type, @chatId, @userId, @source, @sourceUrl, @inputPath, @outputPaths, @mode, @status, @progress, @stage, @attempts, @maxAttempts, @error, @checksum, @telegramMessageId, @metadata, @createdAt, @updatedAt) `).run({ ...job, outputPaths: JSON.stringify(job.outputPaths), metadata: JSON.stringify(job.metadata), createdAt: now, updatedAt: now }); return job; } function mapRow(row) { if (!row) return null; return { id: row.id, type: row.type, chatId: row.chat_id, userId: row.user_id, source: row.source, sourceUrl: row.source_url, inputPath: row.input_path, outputPaths: JSON.parse(row.output_paths || "[]"), mode: row.mode, status: row.status, progress: row.progress, stage: row.stage, attempts: row.attempts, maxAttempts: row.max_attempts, error: row.error, checksum: row.checksum, telegramMessageId: row.telegram_message_id, metadata: JSON.parse(row.metadata || "{}"), createdAt: row.created_at, updatedAt: row.updated_at, startedAt: row.started_at, finishedAt: row.finished_at }; } function getJob(id) { return mapRow(getDb().prepare("SELECT * FROM jobs WHERE id = ?").get(id)); } function listJobs(limit = 50) { return getDb().prepare("SELECT * FROM jobs ORDER BY created_at DESC LIMIT ?").all(limit).map(mapRow); } function nextJob() { return mapRow(getDb().prepare(` SELECT * FROM jobs WHERE status IN ('queued', 'retrying') ORDER BY created_at ASC LIMIT 1 `).get()); } function updateJob(id, patch) { const fields = []; const values = {}; const map = { inputPath: "input_path", outputPaths: "output_paths", telegramMessageId: "telegram_message_id", maxAttempts: "max_attempts", sourceUrl: "source_url" }; for (const [key, value] of Object.entries(patch)) { const column = map[key] || key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); fields.push(`${column} = @${key}`); values[key] = Array.isArray(value) || (value && typeof value === "object") ? JSON.stringify(value) : value; } fields.push("updated_at = @updatedAt"); values.updatedAt = nowIso(); values.id = id; getDb().prepare(`UPDATE jobs SET ${fields.join(", ")} WHERE id = @id`).run(values); return getJob(id); } function event(jobId, level, message, data = {}) { getDb().prepare("INSERT INTO events (job_id, level, message, data, created_at) VALUES (?, ?, ?, ?, ?)") .run(jobId, level, message, JSON.stringify(data), nowIso()); } function listEvents(limit = 200) { return getDb().prepare("SELECT * FROM events ORDER BY id DESC LIMIT ?").all(limit); } module.exports = { createJob, getJob, listJobs, nextJob, updateJob, event, listEvents };