"""
Migration 0002 — feature_flags, email_log, and CMS tables.

Adds:
  - feature_flags: DB-backed feature toggles (admin UI, no restart)
  - email_log: append-only audit trail of all outgoing emails
  - article_templates: Jinja2 body templates for pSEO generation
  - template_data: JSON data rows for bulk article generation
  - articles: CMS article records with FTS5 search
"""

SQL_DDL = """\
CREATE TABLE IF NOT EXISTS feature_flags (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT UNIQUE NOT NULL,
    enabled     INTEGER NOT NULL DEFAULT 0,
    description TEXT,
    updated_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_feature_flags_name ON feature_flags(name);

CREATE TABLE IF NOT EXISTS email_log (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    recipient   TEXT NOT NULL,
    subject     TEXT NOT NULL,
    template    TEXT,
    status      TEXT NOT NULL DEFAULT 'sent',
    provider_id TEXT,
    error       TEXT,
    created_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_email_log_recipient ON email_log(recipient);
CREATE INDEX IF NOT EXISTS idx_email_log_created   ON email_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_email_log_status    ON email_log(status);

CREATE TABLE IF NOT EXISTS article_templates (
    id                       INTEGER PRIMARY KEY AUTOINCREMENT,
    name                     TEXT NOT NULL,
    slug                     TEXT UNIQUE NOT NULL,
    url_pattern              TEXT NOT NULL,
    title_pattern            TEXT NOT NULL,
    meta_description_pattern TEXT,
    body_template            TEXT NOT NULL,
    created_at               TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at               TEXT
);

CREATE INDEX IF NOT EXISTS idx_article_templates_slug ON article_templates(slug);

CREATE TABLE IF NOT EXISTS articles (
    id               INTEGER PRIMARY KEY AUTOINCREMENT,
    url_path         TEXT UNIQUE NOT NULL,
    slug             TEXT UNIQUE NOT NULL,
    title            TEXT NOT NULL,
    meta_description TEXT,
    og_image_url     TEXT,
    status           TEXT NOT NULL DEFAULT 'draft',
    published_at     TEXT,
    template_data_id INTEGER,
    created_at       TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at       TEXT
);

CREATE INDEX IF NOT EXISTS idx_articles_url_path ON articles(url_path);
CREATE INDEX IF NOT EXISTS idx_articles_slug     ON articles(slug);
CREATE INDEX IF NOT EXISTS idx_articles_status   ON articles(status, published_at);

CREATE TABLE IF NOT EXISTS template_data (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    template_id INTEGER NOT NULL REFERENCES article_templates(id),
    data_json   TEXT NOT NULL,
    article_id  INTEGER REFERENCES articles(id),
    created_at  TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at  TEXT
);

CREATE INDEX IF NOT EXISTS idx_template_data_template ON template_data(template_id);

CREATE VIRTUAL TABLE IF NOT EXISTS articles_fts USING fts5(
    title,
    meta_description,
    content='articles',
    content_rowid='id'
)"""

# Triggers are kept separate because split(";") would break BEGIN...END blocks.
SQL_TRIGGERS = [
    """\
CREATE TRIGGER IF NOT EXISTS articles_ai AFTER INSERT ON articles BEGIN
    INSERT INTO articles_fts(rowid, title, meta_description)
    VALUES (new.id, new.title, new.meta_description);
END""",
    """\
CREATE TRIGGER IF NOT EXISTS articles_ad AFTER DELETE ON articles BEGIN
    INSERT INTO articles_fts(articles_fts, rowid, title, meta_description)
    VALUES ('delete', old.id, old.title, old.meta_description);
END""",
    """\
CREATE TRIGGER IF NOT EXISTS articles_au AFTER UPDATE ON articles BEGIN
    INSERT INTO articles_fts(articles_fts, rowid, title, meta_description)
    VALUES ('delete', old.id, old.title, old.meta_description);
    INSERT INTO articles_fts(rowid, title, meta_description)
    VALUES (new.id, new.title, new.meta_description);
END""",
]


def up(conn):
    for statement in SQL_DDL.split(";"):
        stmt = statement.strip()
        if stmt:
            conn.execute(stmt)
    for trigger in SQL_TRIGGERS:
        conn.execute(trigger)
