"""Add email_log and inbound_emails tables for the admin email hub.

email_log tracks every outgoing email (resend_id, delivery events).
inbound_emails stores messages received via Resend webhook (full body stored
locally since inbound payloads can't be re-fetched).
"""


def up(conn):
    conn.execute("""
        CREATE TABLE IF NOT EXISTS email_log (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            resend_id    TEXT,
            from_addr    TEXT NOT NULL,
            to_addr      TEXT NOT NULL,
            subject      TEXT NOT NULL,
            email_type   TEXT NOT NULL DEFAULT 'ad_hoc',
            last_event   TEXT NOT NULL DEFAULT 'sent',
            delivered_at TEXT,
            opened_at    TEXT,
            clicked_at   TEXT,
            bounced_at   TEXT,
            created_at   TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_email_log_resend ON email_log(resend_id)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_email_log_to ON email_log(to_addr)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_email_log_type ON email_log(email_type)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_email_log_created ON email_log(created_at)")

    conn.execute("""
        CREATE TABLE IF NOT EXISTS inbound_emails (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            resend_id   TEXT NOT NULL UNIQUE,
            message_id  TEXT,
            in_reply_to TEXT,
            from_addr   TEXT NOT NULL,
            to_addr     TEXT NOT NULL,
            subject     TEXT,
            text_body   TEXT,
            html_body   TEXT,
            is_read     INTEGER NOT NULL DEFAULT 0,
            received_at TEXT NOT NULL,
            created_at  TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_inbound_resend ON inbound_emails(resend_id)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_inbound_from ON inbound_emails(from_addr)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_inbound_read ON inbound_emails(is_read)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_inbound_received ON inbound_emails(received_at)")
