'use strict';

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

async function insertModuleRun({ connectionId, overallStatus, modules, isDemo = false }) {
  const ins = await pool.query(
    `INSERT INTO ebs_module_runs (connection_id, overall_status, modules_json, is_demo)
     VALUES (:p1, :p2, :p3, :p4)
     RETURNING id INTO :out_id`,
    { p1: connectionId, p2: overallStatus,
      p3: pool.clob(JSON.stringify(modules)), p4: pool.bool(isDemo),
      out_id: pool.outNumber() }
  );
  const result = await pool.query(
    `SELECT id, run_at FROM ebs_module_runs WHERE id = :p1`,
    { p1: ins.outBinds.out_id[0] }
  );
  return result.rows[0];
}

async function getLatestModuleRun(connectionId, userId) {
  const result = await pool.query(
    `SELECT r.id, r.connection_id, r.run_at, r.overall_status, r.modules_json, r.is_demo
     FROM ebs_module_runs r
     JOIN oracle_connections oc ON oc.id = r.connection_id
     WHERE r.connection_id = :p1 AND oc.user_id = :p2
     ORDER BY r.run_at DESC
     FETCH FIRST 1 ROWS ONLY`,
    { p1: connectionId, p2: userId }
  );
  return result.rows[0] || null;
}

module.exports = { insertModuleRun, getLatestModuleRun };
