import { sql } from 'drizzle-orm';
import {
  index,
  integer,
  jsonb,
  pgTable,
  primaryKey,
  text,
  timestamp,
  uniqueIndex,
  uuid,
} from 'drizzle-orm/pg-core';

export const e2eFactoryRuns = pgTable('e2e_factory_runs', {
  runId: uuid('run_id').primaryKey(),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  touchedAt: timestamp('touched_at', { withTimezone: true }).notNull().defaultNow(),
});

export const e2eFactoryCommands = pgTable(
  'e2e_factory_commands',
  {
    runId: uuid('run_id').notNull(),
    requestId: uuid('request_id').notNull(),
    bodyHash: text('body_hash').notNull(),
    operation: text('operation').notNull(),
    result: jsonb('result'),
    completedAt: timestamp('completed_at', { withTimezone: true }),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [
    primaryKey({ columns: [table.runId, table.requestId] }),
    index('e2e_factory_commands_created_at_idx').on(table.createdAt),
  ],
);

export const e2eFactoryEntities = pgTable(
  'e2e_factory_entities',
  {
    runId: uuid('run_id').notNull(),
    kind: text('kind').notNull(),
    entityId: uuid('entity_id').notNull(),
    operation: text('operation').notNull(),
    dependencyOrder: integer('dependency_order').notNull(),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    deletedAt: timestamp('deleted_at', { withTimezone: true }),
  },
  (table) => [
    primaryKey({ columns: [table.runId, table.kind, table.entityId] }),
    uniqueIndex('e2e_factory_entities_active_kind_entity_uq')
      .on(table.kind, table.entityId)
      .where(sql`${table.deletedAt} IS NULL`),
    index('e2e_factory_entities_run_order_idx').on(table.runId, table.dependencyOrder),
  ],
);
