CREATE TABLE IF NOT EXISTS memories (
    id UUID PRIMARY KEY,
    agent_id VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    embedding vector(384) NOT NULL,
    keywords TEXT[] DEFAULT '{}',
    metadata JSONB DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE memories
    ALTER COLUMN agent_id TYPE VARCHAR(255);

ALTER TABLE memories
    ADD COLUMN IF NOT EXISTS keywords TEXT[] DEFAULT '{}';

ALTER TABLE memories
    ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT '{}'::jsonb;

ALTER TABLE memories
    ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW();

ALTER TABLE memories
    ALTER COLUMN keywords SET DEFAULT '{}';

ALTER TABLE memories
    ALTER COLUMN metadata SET DEFAULT '{}'::jsonb;

ALTER TABLE memories
    ALTER COLUMN created_at SET DEFAULT NOW();

CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
CREATE INDEX IF NOT EXISTS idx_memories_embedding ON memories
    USING hnsw (embedding vector_cosine_ops);
