'use strict';

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

async function insertModuleRun({ connectionId, overallStatus, modules, isDemo = false }) {
  const result = await pool.query(
    `INSERT INTO ebs_module_runs (connection_id, overall_status, modules_json, is_demo)
     VALUES ($1, $2, $3, $4)
     RETURNING id, run_at`,
    [connectionId, overallStatus, JSON.stringify(modules), isDemo]
  );
  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 = $1 AND oc.user_id = $2
     ORDER BY r.run_at DESC
     LIMIT 1`,
    [connectionId, userId]
  );
  return result.rows[0] || null;
}

module.exports = { insertModuleRun, getLatestModuleRun };
