import { db, id, json, now } from '../db.js';
import { camelSystemJobAction } from './mappers.js';

export function recordSystemJobAction({
  jobId = null,
  targetType,
  targetId,
  action,
  status,
  message = '',
  actorUserId = null,
  metadata = {}
}) {
  const actionId = id('sja');
  db.prepare(`
    INSERT INTO system_job_actions (
      id, job_id, target_type, target_id, action, status, message,
      actor_user_id, metadata_json, created_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(
    actionId,
    jobId,
    targetType,
    targetId,
    action,
    status,
    message,
    actorUserId,
    json(metadata),
    now()
  );
  return getSystemJobAction(actionId);
}

export function getSystemJobAction(actionId) {
  const row = db.prepare(`
    SELECT a.*, u.display_name AS actor_name
    FROM system_job_actions a
    LEFT JOIN users u ON u.id = a.actor_user_id
    WHERE a.id = ?
  `).get(actionId);
  return row ? camelSystemJobAction(row) : null;
}

export function listSystemJobActions(limit = 200) {
  return db.prepare(`
    SELECT a.*, u.display_name AS actor_name
    FROM system_job_actions a
    LEFT JOIN users u ON u.id = a.actor_user_id
    ORDER BY a.created_at DESC
    LIMIT ?
  `).all(Math.max(1, Math.min(Number(limit) || 200, 500))).map(camelSystemJobAction);
}

