-- MIGRACIÓN Y SEED INICIAL - SISTEMA DE RECONOCIMIENTO

-- 1. Tabla de configuraciones (settings)
CREATE TABLE IF NOT EXISTS settings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    slug TEXT UNIQUE NOT NULL,
    api_url TEXT NOT NULL,
    api_url_timbrada TEXT,
    api_url_pin TEXT,
    login_pin INTEGER DEFAULT 0,
    jwt TEXT NOT NULL,
    empresa_nombre TEXT NOT NULL,
    activo INTEGER DEFAULT 1
);

-- 2. Tabla de usuarios administradores globales
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password_hash TEXT NOT NULL
);

-- 3. Tabla de usuarios por subdominio (slug_users)
CREATE TABLE IF NOT EXISTS slug_users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    slug TEXT NOT NULL,
    username TEXT NOT NULL,
    password_hash TEXT NOT NULL,
    role TEXT NOT NULL,
    UNIQUE(slug, username)
);

-- 4. Tabla de IPs permitidas (whitelist)
CREATE TABLE IF NOT EXISTS allowed_ips (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    slug TEXT NOT NULL,
    ip_address TEXT NOT NULL,
    status TEXT DEFAULT 'pending',
    UNIQUE(slug, ip_address)
);

-- SEED: Usuario admin por defecto (admin / 2026@Fer)
-- Nota: La contraseña ya está hasheada
INSERT OR IGNORE INTO users (username, password_hash) 
VALUES ('admin', 'scrypt:32768:8:1$EAn0mDscv7N8qP8q$3786271a3962d29486c91a0391694f5763568984954867909a341901a0734567...');

-- SEED: Configuración inicial de ejemplo
INSERT OR IGNORE INTO settings (slug, api_url, api_url_timbrada, jwt, empresa_nombre) 
VALUES (
    'fernandoi', 
    'https://fernandoi.kapitalcompany.com/index.php?page=api_rrhh&action=colaboradores_activosConFaceID',
    'https://fernandoi.kapitalcompany.com/index.php?page=api_rrhh&action=registrar_timbradas',
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...',
    'FernandoI'
);
