import { integer, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core';

export const threads = pgTable('library_threads', {
  id: text('id').primaryKey(),
  userId: text('user_id').notNull(),
  title: text('title').notNull(),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  sources: jsonb('sources').$type<string[]>().default([]),
  files: jsonb('files').$type<{ fileId: string; name: string }[]>().default([]),
});

export type Block = { type: string; id?: string; data?: unknown };

export const threadMessages = pgTable('library_thread_messages', {
  id: integer('id').primaryKey().generatedAlwaysAsIdentity(),
  threadId: text('thread_id').notNull().references(() => threads.id, { onDelete: 'cascade' }),
  messageId: text('message_id').notNull(),
  backendId: text('backend_id').notNull().default(''),
  query: text('query').notNull(),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  responseBlocks: jsonb('response_blocks').$type<Block[]>().default([]),
  status: text('status', { enum: ['answering', 'completed', 'error'] }).default('answering'),
});
