-- quotesdb D1 schema migrations
-- Run with: wrangler d1 execute quotesdb --remote --file migrations/schema.sql
-- All CREATE statements are idempotent (IF NOT EXISTS).
-- The ALTER TABLE is not idempotent; errors are expected on re-runs (column already exists).

CREATE TABLE IF NOT EXISTS quotes (
    id         TEXT     PRIMARY KEY,
    text       TEXT     NOT NULL,
    author     TEXT     NOT NULL,
    source     TEXT,
    date       TEXT,
    auth_code  TEXT     NOT NULL,
    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)
);

CREATE INDEX IF NOT EXISTS idx_quote_tags_quote_id ON quote_tags(quote_id);

CREATE INDEX IF NOT EXISTS idx_quotes_author ON quotes(author COLLATE NOCASE);

CREATE TABLE IF NOT EXISTS admin_config (
    key   TEXT PRIMARY KEY,
    value TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS reports (
    id         TEXT     PRIMARY KEY,
    quote_id   TEXT     NOT NULL REFERENCES quotes(id) ON DELETE CASCADE,
    reason     TEXT,
    created_at TEXT     NOT NULL DEFAULT (datetime('now'))
);

-- Add hidden column to existing databases (ignore error if column already exists).
ALTER TABLE quotes ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0;
