CREATE TABLE IF NOT EXISTS "chat_file_references" (
  "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
  "file_id" uuid NOT NULL,
  "conversation_id" uuid NOT NULL,
  "message_id" uuid,
  "created_at" timestamp with time zone DEFAULT now() NOT NULL,
  CONSTRAINT "chat_file_references_file_id_chat_files_id_fk" FOREIGN KEY ("file_id") REFERENCES "chat_files"("id") ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT "chat_file_references_conversation_id_chat_conversations_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "chat_conversations"("id") ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT "chat_file_references_message_id_chat_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "chat_messages"("id") ON DELETE SET NULL ON UPDATE NO ACTION
);

CREATE INDEX IF NOT EXISTS "chat_file_refs_file_idx" ON "chat_file_references" ("file_id");
CREATE INDEX IF NOT EXISTS "chat_file_refs_conversation_idx" ON "chat_file_references" ("conversation_id");
CREATE INDEX IF NOT EXISTS "chat_file_refs_message_idx" ON "chat_file_references" ("message_id");
