-- quotesdb D1 schema — idempotent, safe to re-apply.
-- Apply with: wrangler d1 execute quotesdb --file infra/schema.sql --remote
-- Local dev:  wrangler d1 execute quotesdb --file infra/schema.sql --local

CREATE TABLE IF NOT EXISTS quotes (
  id         TEXT PRIMARY KEY,                         -- UUID v4
  text       TEXT NOT NULL,
  author     TEXT NOT NULL,
  source     TEXT,                                     -- optional: book, speech, etc.
  date       TEXT,                                     -- optional: ISO date YYYY-MM-DD
  auth_code  TEXT NOT NULL,                            -- 4-word passphrase (plaintext)
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS quote_tags (
  quote_id TEXT NOT NULL REFERENCES quotes(id) ON DELETE CASCADE,
  tag      TEXT NOT NULL,
  PRIMARY KEY (quote_id, tag)
);

-- Index for efficient author-filtered queries (case-insensitive).
CREATE INDEX IF NOT EXISTS idx_quotes_author ON quotes(author COLLATE NOCASE);

-- Index for efficient tag lookups by quote ID.
CREATE INDEX IF NOT EXISTS idx_quote_tags_quote_id ON quote_tags(quote_id);
