-- 001_initial_schema.sql — Schema base de Pedrito Hechakuaa
-- Idempotente: usa CREATE TABLE/INDEX IF NOT EXISTS

CREATE TABLE IF NOT EXISTS schema_migrations (
    version    TEXT PRIMARY KEY,
    applied_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS invite_codes (
    codigo     TEXT PRIMARY KEY,
    creado_at  TEXT NOT NULL,
    usado      INTEGER DEFAULT 0,
    usado_por  INTEGER,
    usado_at   TEXT
);

CREATE TABLE IF NOT EXISTS tenants (
    chat_id                 INTEGER PRIMARY KEY,
    nombre_preferido        TEXT,
    tono                    TEXT    DEFAULT 'cotidiano',
    timezone                TEXT    DEFAULT 'America/Asuncion',
    credentials_enc         TEXT,
    estado                  TEXT    DEFAULT 'pendiente',
    consentimiento_aceptado INTEGER DEFAULT 0,
    created_at              TEXT,
    last_active             TEXT
);

CREATE TABLE IF NOT EXISTS audit_log (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp       TEXT    NOT NULL,
    timestamp_local TEXT,
    chat_id         INTEGER,
    evento          TEXT    NOT NULL,
    detalle         TEXT,
    resultado       TEXT,
    duracion_ms     INTEGER
);

CREATE INDEX IF NOT EXISTS idx_audit_chat_id   ON audit_log(chat_id);
CREATE INDEX IF NOT EXISTS idx_audit_timestamp ON audit_log(timestamp);
CREATE INDEX IF NOT EXISTS idx_audit_evento    ON audit_log(evento);
