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

import { tenants } from "./tenants"
import { authUsers } from "./auth_users"
import { files } from "./files"
import { instanceAgents } from "./instance_agents"

export const instanceAgentScanJobs = pgTable("instance_agent_scan_jobs", {
    id: uuid("id").primaryKey().defaultRandom(),

    createdAt: timestamp("created_at", { withTimezone: true })
        .notNull()
        .defaultNow(),

    updatedAt: timestamp("updated_at", { withTimezone: true })
        .notNull()
        .defaultNow(),

    tenantId: bigint("tenant_id", { mode: "number" })
        .notNull()
        .references(() => tenants.id, { onDelete: "cascade", onUpdate: "cascade" }),

    agentId: uuid("agent_id")
        .notNull()
        .references(() => instanceAgents.id, { onDelete: "cascade", onUpdate: "cascade" }),

    requestedBy: uuid("requested_by").references(() => authUsers.id, {
        onDelete: "set null",
        onUpdate: "cascade",
    }),

    status: text("status").notNull().default("pending"),
    scannerName: text("scanner_name"),
    requestedFilename: text("requested_filename"),

    settings: jsonb("settings").notNull().default({}),
    target: jsonb("target").notNull().default({}),
    agentMessage: text("agent_message"),

    attempts: integer("attempts").notNull().default(0),
    claimedAt: timestamp("claimed_at", { withTimezone: true }),
    finishedAt: timestamp("finished_at", { withTimezone: true }),

    fileId: uuid("file_id").references(() => files.id, {
        onDelete: "set null",
        onUpdate: "cascade",
    }),
})

export type InstanceAgentScanJob = typeof instanceAgentScanJobs.$inferSelect
export type NewInstanceAgentScanJob = typeof instanceAgentScanJobs.$inferInsert
