-- Початкова схема ai_memory (див. нотатку "Модель даних")
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS projects (
  id          bigserial PRIMARY KEY,
  name        text NOT NULL UNIQUE,
  summary     text,
  status      text NOT NULL DEFAULT 'active',
  metadata    jsonb NOT NULL DEFAULT '{}',
  created_at  timestamptz NOT NULL DEFAULT now(),
  updated_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS memories (
  id          bigserial PRIMARY KEY,
  project_id  bigint REFERENCES projects(id) ON DELETE CASCADE,
  type        text NOT NULL DEFAULT 'note',
  title       text NOT NULL,
  content     text NOT NULL DEFAULT '',
  content_tsv tsvector GENERATED ALWAYS AS (
    to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(content, ''))
  ) STORED,
  embedding   vector(1024),
  metadata    jsonb NOT NULL DEFAULT '{}',
  created_at  timestamptz NOT NULL DEFAULT now(),
  updated_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS memories_tsv_idx ON memories USING gin (content_tsv);
CREATE INDEX IF NOT EXISTS memories_project_idx ON memories (project_id);
CREATE INDEX IF NOT EXISTS memories_type_idx ON memories (type);

CREATE TABLE IF NOT EXISTS memory_links (
  source_id  bigint NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
  target_id  bigint NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
  link_type  text NOT NULL DEFAULT 'related',
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (source_id, target_id, link_type)
);

CREATE INDEX IF NOT EXISTS memory_links_target_idx ON memory_links (target_id);

CREATE TABLE IF NOT EXISTS sessions (
  id                 bigserial PRIMARY KEY,
  project_id         bigint NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
  session_summary    text,
  todo_json          jsonb NOT NULL DEFAULT '{"tasks": []}',
  changes            text,
  bugs               text,
  architecture_notes text,
  created_at         timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS sessions_project_idx ON sessions (project_id, created_at DESC);
