CREATE TABLE IF NOT EXISTS "chat_files" (
  "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
  "company_id" uuid NOT NULL,
  "conversation_id" uuid,
  "message_id" uuid,
  "filename" text NOT NULL,
  "original_filename" text NOT NULL,
  "mime_type" text NOT NULL,
  "size_bytes" integer NOT NULL,
  "object_key" text NOT NULL,
  "sha256" text NOT NULL,
  "source" text NOT NULL,
  "category" text,
  "project_id" uuid,
  "created_at" timestamp with time zone DEFAULT now() NOT NULL,
  "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
  CONSTRAINT "chat_files_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "companies"("id") ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT "chat_files_conversation_id_chat_conversations_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "chat_conversations"("id") ON DELETE SET NULL ON UPDATE NO ACTION,
  CONSTRAINT "chat_files_message_id_chat_messages_id_fk" FOREIGN KEY ("message_id") REFERENCES "chat_messages"("id") ON DELETE SET NULL ON UPDATE NO ACTION,
  CONSTRAINT "chat_files_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE SET NULL ON UPDATE NO ACTION
);

CREATE INDEX IF NOT EXISTS "chat_files_conversation_idx" ON "chat_files" ("conversation_id");
CREATE INDEX IF NOT EXISTS "chat_files_message_idx" ON "chat_files" ("message_id");
CREATE INDEX IF NOT EXISTS "chat_files_company_created_idx" ON "chat_files" ("company_id", "created_at");
CREATE INDEX IF NOT EXISTS "chat_files_project_idx" ON "chat_files" ("project_id");
