CREATE TABLE IF NOT EXISTS rag_chat_attachment (
    id BIGSERIAL PRIMARY KEY,
    attachment_id VARCHAR(64) NOT NULL UNIQUE,
    conversation_id VARCHAR(64) NOT NULL,
    user_id BIGINT NOT NULL,
    tenant_code VARCHAR(64) NULL,
    area VARCHAR(255) NULL,
    filename VARCHAR(512) NOT NULL,
    original_name VARCHAR(512) NOT NULL,
    content_type VARCHAR(255) NULL,
    file_size BIGINT NOT NULL DEFAULT 0,
    minio_path TEXT NULL,
    collection_name VARCHAR(160) NOT NULL,
    indexing_status VARCHAR(32) NOT NULL DEFAULT 'waiting',
    indexing_error TEXT NULL,
    chunk_count INTEGER NOT NULL DEFAULT 0,
    indexing_started_at TIMESTAMPTZ NULL,
    indexing_completed_at TIMESTAMPTZ NULL,
    expires_at TIMESTAMPTZ NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ NULL
);

CREATE INDEX IF NOT EXISTS idx_rag_chat_attachment_scope
ON rag_chat_attachment(tenant_code, user_id, conversation_id, attachment_id)
WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_rag_chat_attachment_expires
ON rag_chat_attachment(expires_at)
WHERE deleted_at IS NULL;
