import { pgTable, pgEnum, uuid, text, timestamp, jsonb, bigint } from "drizzle-orm/pg-core";
import { users } from "./users";

// Remote machines that report in so Ampelos knows whether their storage is
// reachable. Backup/archive media lives on hosts that are not always powered
// on, and probing an unmounted path would otherwise look like mass data loss.
// One row per agent, updated in place on every heartbeat.
export const agentHeartbeats = pgTable("agent_heartbeats", {
  id: uuid("id").primaryKey().defaultRandom(),
  // Stable agent name, e.g. "silenus". Matches storage_tiers.agent_name.
  agent: text("agent").notNull().unique(),
  hostname: text("hostname"),
  version: text("version"),
  firstSeenAt: timestamp("first_seen_at").notNull().defaultNow(),
  lastSeenAt: timestamp("last_seen_at").notNull().defaultNow(),
  // Whatever the agent chooses to report: mounted paths, free space, GPU
  // presence, load. Shape is owned by the agent, not by this schema.
  details: jsonb("details"),
});

export const corruptFileStatusEnum = pgEnum("corrupt_file_status", [
  "pending",
  "approved",
  "deleted",
  "dismissed",
  "failed",
]);

// Files an agent found to be unreadable — a container that probes but will not
// decode, or one ffprobe cannot open at all.
//
// Deletion is deliberately split from detection. Ampelos owns the decision and
// records the human approval; the reporting agent performs the removal, because
// Ampelos mounts these tiers read-only so that no scan can ever damage the
// backup. Nothing is removed without an explicit approval recorded here.
export const corruptFiles = pgTable("corrupt_files", {
  id: uuid("id").primaryKey().defaultRandom(),
  // Absolute path as the reporting agent sees it; that is the path it will be
  // asked to delete. Unique so repeated runs update rather than duplicate.
  fullPath: text("full_path").notNull().unique(),
  agent: text("agent").notNull(),
  tier: text("tier"),
  reason: text("reason").notNull(),
  sizeBytes: bigint("size_bytes", { mode: "bigint" }),
  status: corruptFileStatusEnum("status").notNull().default("pending"),
  firstDetectedAt: timestamp("first_detected_at").notNull().defaultNow(),
  lastDetectedAt: timestamp("last_detected_at").notNull().defaultNow(),
  reviewedBy: uuid("reviewed_by").references(() => users.id),
  reviewedAt: timestamp("reviewed_at"),
  deletedAt: timestamp("deleted_at"),
  // Last failure from the agent's delete attempt; cleared on success.
  deleteError: text("delete_error"),
});
