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

export const taskLogs = pgTable('task_logs', {
  id: serial('id').primaryKey(),
  userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
  taskName: text('task_name').notNull(),
  taskDirName: text('task_dir_name').notNull(),
  entryName: text('entry_name').notNull(),
  entryType: text('entry_type').notNull(),
  provider: text('provider').notNull(),
  model: text('model').notNull(),
  isError: boolean('is_error').notNull().default(false),
  messages: jsonb('messages').notNull().default([]),
  startedAt: timestamp('started_at', { withTimezone: true }).notNull(),
  completedAt: timestamp('completed_at', { withTimezone: true }),
}, (table) => [
  index('idx_task_logs_user_started').on(table.userId, table.startedAt),
]);

export const queueJobs = pgTable('queue_jobs', {
  id: text('id').primaryKey(),
  userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
  lane: text('lane').notNull(),
  type: text('type').notNull(),
  status: text('status', { enum: ['queued', 'running', 'completed', 'failed', 'cancelled'] }).notNull().default('queued'),
  currentStep: integer('current_step').notNull().default(0),
  steps: jsonb('steps').notNull().default([]),
  meta: jsonb('meta'),
  error: text('error'),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  startedAt: timestamp('started_at', { withTimezone: true }),
  completedAt: timestamp('completed_at', { withTimezone: true }),
}, (table) => [
  index('idx_queue_jobs_status_lane').on(table.status, table.lane),
  index('idx_queue_jobs_user').on(table.userId),
]);

export const terminalContainers = pgTable('terminal_containers', {
  userId: integer('user_id').primaryKey().references(() => users.id, { onDelete: 'cascade' }),
  dockerId: text('docker_id').notNull(),
  port: integer('port').notNull(),
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});
