import { pgTable, pgEnum, uuid, text, integer, timestamp, jsonb, index } from "drizzle-orm/pg-core";

export const maintenanceJobStatusEnum = pgEnum("maintenance_job_status", [
  "running",
  "succeeded",
  "failed",
  "skipped",
]);

export const maintenanceTriggerEnum = pgEnum("maintenance_trigger", [
  "scheduled",
  "manual",
]);

// One row per attempt of a maintenance job, written by the ampelos-maintenance
// container. This is the durable job history the system has been missing: until
// now every scan, probe and metadata refresh was an ad-hoc `npm run` whose
// outcome existed only in someone's terminal scrollback.
//
// "skipped" is a first-class outcome, not a failure. Backup and archive live on
// a host that is powered off most of the time, and a scan that declines to run
// because its tier is unreachable is behaving correctly — recording it as failed
// would make a healthy system look broken every single night.
export const maintenanceJobs = pgTable(
  "maintenance_jobs",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    // Registry key, e.g. "scan:tv:backup" or "policy:classify".
    job: text("job").notNull(),
    trigger: maintenanceTriggerEnum("trigger").notNull().default("scheduled"),
    status: maintenanceJobStatusEnum("status").notNull().default("running"),
    startedAt: timestamp("started_at").notNull().defaultNow(),
    completedAt: timestamp("completed_at"),
    durationMs: integer("duration_ms"),
    exitCode: integer("exit_code"),
    // Why a run was skipped, or the failure reason.
    detail: text("detail"),
    // Tail of the job's own output, kept small on purpose.
    output: text("output"),
    // Structured summary when the job emits one.
    summary: jsonb("summary"),
  },
  (t) => [
    index("maintenance_jobs_job_started_idx").on(t.job, t.startedAt),
  ],
);
