import { pgTable, uuid, text, integer, timestamp, index } from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { chatConversations } from "./chat_conversations.js";
import { chatMessages } from "./chat_messages.js";
import { projects } from "./projects.js";

export const chatFiles = pgTable(
  "chat_files",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    companyId: uuid("company_id").notNull().references(() => companies.id),
    conversationId: uuid("conversation_id").references(() => chatConversations.id, { onDelete: "set null" }),
    messageId: uuid("message_id").references(() => chatMessages.id, { onDelete: "set null" }),
    filename: text("filename").notNull(),
    originalFilename: text("original_filename").notNull(),
    mimeType: text("mime_type").notNull(),
    sizeBytes: integer("size_bytes").notNull(),
    objectKey: text("object_key").notNull(),
    sha256: text("sha256").notNull(),
    source: text("source").notNull(),
    category: text("category"),
    projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => ({
    conversationIdx: index("chat_files_conversation_idx").on(table.conversationId),
    messageIdx: index("chat_files_message_idx").on(table.messageId),
    companyCreatedIdx: index("chat_files_company_created_idx").on(table.companyId, table.createdAt),
    projectIdx: index("chat_files_project_idx").on(table.projectId),
  }),
);
