import { db, makeUser, adminUserId, load } from './setup.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';

const { listJobs, getJob } = await load('../models/jobModel.js');

const owner = makeUser({ email: 'job-owner@test.local' });
const stranger = makeUser({ email: 'job-stranger@test.local' });
const admin = adminUserId();

// Build a personal RunPlan owned by `owner` and a job they triggered, directly
// in SQL so the test never invokes PowerShell.
const ts = new Date().toISOString();
const scriptId = 'scr_job_test';
db.prepare(`INSERT INTO scripts (id, name, content, visibility, owner_user_id, version, created_at, updated_at)
  VALUES (?, 'Job Test', 'Write-Output 1', 'personal', ?, 1, ?, ?)`).run(scriptId, owner, ts, ts);
const runplanId = 'run_job_test';
db.prepare(`INSERT INTO runplans (id, name, script_id, visibility, owner_user_id, parallel, created_at, updated_at)
  VALUES (?, 'Job Test Plan', ?, 'personal', ?, 1, ?, ?)`).run(runplanId, scriptId, owner, ts, ts);
const jobId = 'job_test_1';
db.prepare(`INSERT INTO jobs (id, runplan_id, script_id, status, triggered_by, created_at)
  VALUES (?, ?, ?, 'completed', ?, ?)`).run(jobId, runplanId, scriptId, owner, ts);
const scriptTestJobId = 'job_script_test_1';
db.prepare(`INSERT INTO jobs (id, runplan_id, script_id, status, triggered_by, created_at)
  VALUES (?, NULL, ?, 'failed', ?, ?)`).run(scriptTestJobId, scriptId, owner, ts);

test('the triggering operator can list and read their job', () => {
  assert.ok(listJobs(owner, false).some((j) => j.id === jobId));
  assert.ok(getJob(jobId, owner, false));
});

test('script test jobs without a RunPlan stay visible to their triggering operator', () => {
  assert.ok(listJobs(owner, false).some((j) => j.id === scriptTestJobId));
  const job = getJob(scriptTestJobId, owner, false);
  assert.equal(job.id, scriptTestJobId);
  assert.equal(job.runplanId, null);
});

test('an unrelated user cannot see a personal job', () => {
  assert.ok(!listJobs(stranger, false).some((j) => j.id === jobId));
  assert.equal(getJob(jobId, stranger, false), null);
});

test('admins can see any job', () => {
  assert.ok(listJobs(admin, true).some((j) => j.id === jobId));
  assert.ok(getJob(jobId, admin, true));
});
