CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pubkey TEXT NOT NULL UNIQUE,
    username TEXT NOT NULL UNIQUE COLLATE NOCASE,
    subscription_type TEXT NOT NULL,
    expires_at TEXT,
    is_active INTEGER NOT NULL DEFAULT 1,
    manual_username INTEGER NOT NULL DEFAULT 0,
    last_synced_at TEXT,
    expiring_reminder_sent_at TEXT,
    deactivated_at TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_users_active ON users(is_active);
CREATE INDEX idx_users_expires ON users(expires_at);
CREATE INDEX idx_users_deactivated ON users(deactivated_at);

CREATE TABLE pending_invoices (
    payment_hash TEXT PRIMARY KEY,
    payment_request TEXT NOT NULL,
    username TEXT NOT NULL,
    pubkey TEXT NOT NULL,
    subscription_type TEXT NOT NULL,
    years INTEGER NOT NULL DEFAULT 1,
    amount_sats INTEGER NOT NULL,
    expires_at TEXT NOT NULL,
    paid INTEGER NOT NULL DEFAULT 0,
    is_renewal INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_pending_unpaid ON pending_invoices(paid, expires_at);
CREATE INDEX idx_pending_username ON pending_invoices(username, paid);

CREATE TABLE webhook_outbox (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    event_type TEXT NOT NULL,
    payload TEXT NOT NULL,
    attempts INTEGER NOT NULL DEFAULT 0,
    last_attempt_at TEXT,
    next_attempt_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    status TEXT NOT NULL DEFAULT 'pending',
    last_error TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_webhook_outbox_pending ON webhook_outbox(status, next_attempt_at);

CREATE TABLE dm_outbox (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    event_type TEXT NOT NULL,
    pubkey TEXT NOT NULL,
    content TEXT NOT NULL,
    attempts INTEGER NOT NULL DEFAULT 0,
    last_attempt_at TEXT,
    next_attempt_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    status TEXT NOT NULL DEFAULT 'pending',
    last_error TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_dm_outbox_pending ON dm_outbox(status, next_attempt_at);
CREATE INDEX idx_dm_outbox_pubkey ON dm_outbox(pubkey, event_type);

CREATE TABLE audit_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    action TEXT NOT NULL,
    actor TEXT NOT NULL,
    pubkey TEXT,
    details TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
