import { pgTable, uuid, jsonb, timestamp, index } from 'drizzle-orm/pg-core';
import { projects } from './projects';

export const flows = pgTable(
  'flows',
  {
    id: uuid('id').primaryKey().defaultRandom(),

    // Relations
    projectId: uuid('project_id')
      .notNull()
      .references(() => projects.id, { onDelete: 'cascade' }),

    // Flow-scoped named aliases (user-assigned only)
    // Technical aliases (@last, @first, @upload) computed programmatically
    // Format: { "@hero": "image-uuid", "@product": "image-uuid" }
    aliases: jsonb('aliases').$type<Record<string, string>>().notNull().default({}),

    // Flexible metadata storage
    meta: jsonb('meta').$type<Record<string, unknown>>().notNull().default({}),

    // Timestamps
    createdAt: timestamp('created_at').notNull().defaultNow(),
    // Updates on every generation/upload activity within this flow
    updatedAt: timestamp('updated_at')
      .notNull()
      .defaultNow()
      .$onUpdate(() => new Date()),
  },
  (table) => ({
    // Index for querying flows by project, ordered by most recent
    projectCreatedAtIdx: index('idx_flows_project').on(table.projectId, table.createdAt.desc()),
  }),
);

export type Flow = typeof flows.$inferSelect;
export type NewFlow = typeof flows.$inferInsert;
