import { pgTable, text, integer, timestamp, jsonb, index } from 'drizzle-orm/pg-core';
import { users } from '../auth/schema';

export const pipelineJobs = pgTable(
  'pipeline_jobs',
  {
    id: text('id').primaryKey(),
    userId: integer('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    taskDirName: text('task_dir_name').notNull(),
    taskName: text('task_name').notNull(),
    // Job kind — pipeline (multi-step agentic), script (single bash/py/ts task), later agentic. (Legacy
    // rows may still carry mode 'download' from before video/audio downloads moved to a script capability.)
    mode: text('mode', { enum: ['pipeline', 'script', 'agentic'] })
      .notNull()
      .default('pipeline'),
    status: text('status', { enum: ['pending', 'running', 'completed', 'failed', 'stopped', 'interrupted'] })
      .notNull()
      .default('pending'),
    inputs: jsonb('inputs').notNull().default({}),
    cwd: text('cwd'),
    config: jsonb('config').notNull(),
    progress: jsonb('progress'),
    totalCost: jsonb('total_cost'),
    error: text('error'),
    // Script jobs: the process exit code (null until finished / for non-script jobs).
    exitCode: integer('exit_code'),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    startedAt: timestamp('started_at', { withTimezone: true }),
    completedAt: timestamp('completed_at', { withTimezone: true }),
  },
  (table) => [
    index('idx_pipeline_jobs_user_created').on(table.userId, table.createdAt),
    index('idx_pipeline_jobs_status').on(table.status),
  ],
);
