import 'package:weblibre/features/geckoview/features/tabs/features/vector_store/data/models/vector_result.dart';

CREATE TABLE document(
  document_id TEXT NOT NULL PRIMARY KEY,
  main_document_id TEXT,
  context_id TEXT,
  content TEXT NOT NULL,
  content_hash TEXT NOT NULL,
  metadata TEXT
);

CREATE INDEX document_main_document_id ON document (main_document_id);
CREATE INDEX document_context_id ON document (context_id);

CREATE TABLE document_vec(
  -- dummy definition of virtual table
  -- keep in sync with defined table definition

  id TEXT NOT NULL PRIMARY KEY,
  main_document_id TEXT,
  context_id TEXT,
  embedding BLOB NOT NULL,
  content_hash TEXT NOT NULL,

  distance REAL,
  k INTEGER
);

CREATE TRIGGER document_delete AFTER DELETE ON document BEGIN
  DELETE FROM document_vec WHERE id = old.document_id;
END;

CREATE TRIGGER document_update_delete AFTER UPDATE ON document BEGIN
  DELETE FROM document_vec WHERE id = new.document_id AND content_hash != new.content_hash;
END;

missingDocumentEmbeddings(
  :main_document_id AS TEXT OR NULL,
  :context_id AS TEXT OR NULL
):
  SELECT
    doc.*
  FROM document doc
  WHERE 
    doc.main_document_id IS COALESCE(:main_document_id, doc.main_document_id) AND
    doc.context_id IS COALESCE(:context_id, doc.context_id) AND
    NOT EXISTS (
      SELECT 1 
      FROM document_vec vec
      WHERE vec.id = doc.document_id
    );

queryVectors(
  :searchVectors AS BLOB, 
  :main_document_id AS TEXT OR NULL,
  :context_id AS TEXT OR NULL
) WITH VectorResult:
  SELECT
    vec.id,
    doc.main_document_id,
    doc.context_id,
    doc.content,
    doc.metadata,
    vec.distance
  FROM document_vec vec
  INNER JOIN document doc ON doc.document_id = vec.id
  WHERE 
    vec.embedding MATCH :searchVectors AND
    vec.k = :k AND
    vec.main_document_id IS COALESCE(:main_document_id, vec.main_document_id) AND
    vec.context_id IS COALESCE(:context_id, vec.context_id)
  ORDER BY vec.distance;