'use strict';

const pool = require('./index');

async function createJob(connectionId, opKey, userId) {
  const { rows } = await pool.query(
    `INSERT INTO ebs_jobs (connection_id, op_key, created_by)
     VALUES ($1, $2, $3) RETURNING id`,
    [connectionId, opKey, userId]
  );
  return { id: rows[0].id };
}

async function startJob(jobId) {
  await pool.query(
    `UPDATE ebs_jobs SET status = 'running', started_at = NOW()
     WHERE id = $1 AND status = 'queued'`,
    [jobId]
  );
}

async function completeJob(jobId, { ok, stdout, exit_code, duration_ms }) {
  const { rowCount } = await pool.query(
    `UPDATE ebs_jobs
     SET status = 'done', ok = $2, stdout = $3, exit_code = $4,
         duration_ms = $5, finished_at = NOW()
     WHERE id = $1`,
    [jobId, ok, stdout, exit_code, duration_ms]
  );
  return rowCount || 0;
}

async function getJob(jobId) {
  const { rows } = await pool.query(
    `SELECT *, created_by AS owner_id FROM ebs_jobs WHERE id = $1`,
    [jobId]
  );
  return rows[0] || null;
}

async function timeoutStaleJobs() {
  const { rowCount } = await pool.query(
    `UPDATE ebs_jobs SET status = 'timeout', finished_at = NOW()
     WHERE status IN ('queued','running')
       AND created_at < NOW() - INTERVAL '75 minutes'`
  );
  return rowCount || 0;
}

async function getRunningJobs() {
  const { rows } = await pool.query(
    `SELECT id, connection_id FROM ebs_jobs WHERE status = 'running'`
  );
  return rows;
}

async function updateJobLogTail(jobId, logTail) {
  await pool.query(
    `UPDATE ebs_jobs SET log_tail = $2 WHERE id = $1`,
    [jobId, logTail]
  );
}

async function cancelJob(jobId, logTail) {
  await pool.query(
    `UPDATE ebs_jobs SET status = 'cancelled', finished_at = NOW(), log_tail = COALESCE($2, log_tail)
     WHERE id = $1 AND status IN ('queued', 'running')`,
    [jobId, logTail || null]
  );
}

async function getActiveJobForConnection(connectionId) {
  const { rows } = await pool.query(
    `SELECT id, op_key FROM ebs_jobs WHERE connection_id = $1 AND status IN ('queued', 'running') LIMIT 1`,
    [connectionId]
  );
  return rows[0] || null;
}

module.exports = { createJob, startJob, completeJob, getJob, timeoutStaleJobs, getRunningJobs, updateJobLogTail, cancelJob, getActiveJobForConnection };
