import test from "node:test";
import assert from "node:assert/strict";
import { computeCaptureProgress, deriveCaptureStatus } from "@/lib/capture/status";

test("computeCaptureProgress marks complete when all capture signals exist", () => {
  const result = computeCaptureProgress({
    objectiveIndicator: "Meta semanal",
    quantityQuality: "https://drive.google.com/file/abc",
    compliance: "88%",
    compliancePct: 88,
    dueCommitment: "Update martes",
  });

  assert.equal(result.isComplete, true);
  assert.equal(result.isPartial, true);
});

test("deriveCaptureStatus returns error when auto run failed without newer success", () => {
  const now = new Date("2026-03-23T12:00:00.000Z");
  const status = deriveCaptureStatus({
    captureMode: "auto",
    freshnessSlaHours: 48,
    latestRunStatus: "failed",
    latestRunAt: "2026-03-23T11:00:00.000Z",
    latestSuccessfulRunAt: "2026-03-22T10:00:00.000Z",
    now,
  });

  assert.equal(status, "error");
});

test("deriveCaptureStatus returns captured when complete and fresh", () => {
  const now = new Date("2026-03-23T12:00:00.000Z");
  const status = deriveCaptureStatus({
    captureMode: "manual",
    freshnessSlaHours: 168,
    objectiveIndicator: "Objetivo",
    quantityQuality: "Evidencia",
    compliance: "90%",
    compliancePct: 90,
    dueCommitment: "Compromiso",
    lastCapturedAt: "2026-03-22T09:00:00.000Z",
    now,
  });

  assert.equal(status, "captured");
});

test("deriveCaptureStatus returns stale when complete but outside SLA", () => {
  const now = new Date("2026-03-23T12:00:00.000Z");
  const status = deriveCaptureStatus({
    captureMode: "manual",
    freshnessSlaHours: 1,
    objectiveIndicator: "Objetivo",
    quantityQuality: "Evidencia",
    compliance: "90%",
    compliancePct: 90,
    dueCommitment: "Compromiso",
    lastCapturedAt: "2026-03-23T08:00:00.000Z",
    now,
  });

  assert.equal(status, "stale");
});

test("deriveCaptureStatus returns in_progress for partial manual capture", () => {
  const now = new Date("2026-03-23T12:00:00.000Z");
  const status = deriveCaptureStatus({
    captureMode: "manual",
    freshnessSlaHours: 168,
    objectiveIndicator: "Solo objetivo",
    now,
  });

  assert.equal(status, "in_progress");
});

test("deriveCaptureStatus returns pending when no activity exists", () => {
  const now = new Date("2026-03-23T12:00:00.000Z");
  const status = deriveCaptureStatus({
    captureMode: "manual",
    freshnessSlaHours: 168,
    now,
  });

  assert.equal(status, "pending");
});

test("deriveCaptureStatus returns stale for auto rows when last successful run is outside SLA", () => {
  const now = new Date("2026-03-23T12:00:00.000Z");
  const status = deriveCaptureStatus({
    captureMode: "auto",
    freshnessSlaHours: 2,
    latestRunStatus: "success",
    latestRunAt: "2026-03-23T08:00:00.000Z",
    latestSuccessfulRunAt: "2026-03-23T08:00:00.000Z",
    now,
  });

  assert.equal(status, "stale");
});
