import { type AnyPgColumn, pgTable, uuid, text, timestamp, index } from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { agents } from "./agents.js";

export const chatConversations = pgTable(
  "chat_conversations",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    companyId: uuid("company_id").notNull().references(() => companies.id),
    title: text("title"),
    agentId: uuid("agent_id").references(() => agents.id, { onDelete: "set null" }),
    pinnedAt: timestamp("pinned_at", { withTimezone: true }),
    archivedAt: timestamp("archived_at", { withTimezone: true }),
    deletedAt: timestamp("deleted_at", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
    parentConversationId: uuid("parent_conversation_id").references((): AnyPgColumn => chatConversations.id, { onDelete: "set null" }),
    branchFromMessageId: uuid("branch_from_message_id"),
  },
  (table) => ({
    companyUpdatedIdx: index("chat_conversations_company_updated_idx").on(table.companyId, table.updatedAt),
    companyDeletedIdx: index("chat_conversations_company_deleted_idx").on(table.companyId, table.deletedAt),
    parentIdx: index("chat_conversations_parent_idx").on(table.parentConversationId),
  }),
);
