import { pgTable, uuid, text, timestamp, jsonb, index } from "drizzle-orm/pg-core";
import { companies } from "./companies.js";

export const CONTENT_JOB_STATUSES = ["queued", "running", "done", "failed"] as const;
export type ContentJobStatus = (typeof CONTENT_JOB_STATUSES)[number];

export const contentJobs = pgTable(
  "content_jobs",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    companyId: uuid("company_id").notNull().references(() => companies.id),
    jobType: text("job_type").notNull(),
    status: text("status").$type<ContentJobStatus>().notNull().default("queued"),
    input: jsonb("input").notNull().default({}),
    resultAssetId: uuid("result_asset_id"),
    errorMessage: text("error_message"),
    sourceTaskId: text("source_task_id"),
    startedAt: timestamp("started_at", { withTimezone: true }),
    finishedAt: timestamp("finished_at", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => ({
    content_jobs_company_status_idx: index("content_jobs_company_status_idx").on(
      table.companyId,
      table.status,
    ),
    content_jobs_company_created_idx: index("content_jobs_company_created_idx").on(
      table.companyId,
      table.createdAt,
    ),
  }),
);
