-- Remote access control plane (WireGuard v1, reverse SSH reserved).
-- MariaDB / production: mysql -u root -p androidcast_crashes < sql/migrations/007_remote_access.sql

CREATE TABLE IF NOT EXISTS remote_access_devices (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    device_id VARCHAR(128) NOT NULL,
    company_id INT UNSIGNED NOT NULL DEFAULT 1,
    whitelisted TINYINT(1) NOT NULL DEFAULT 0,
    opt_in_mode ENUM('none','wireguard','rssh') NOT NULL DEFAULT 'none',
    last_random VARCHAR(96) NULL,
    app_version VARCHAR(64) NULL,
    last_seen_at TIMESTAMP NULL,
    notes TEXT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_ra_device (device_id),
    KEY idx_ra_device_company (company_id),
    KEY idx_ra_device_whitelist (whitelisted, opt_in_mode)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS remote_access_sessions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(36) NOT NULL,
    device_id VARCHAR(128) NOT NULL,
    company_id INT UNSIGNED NOT NULL DEFAULT 1,
    operator_user_id INT UNSIGNED NULL,
    status ENUM('pending','active','inactive','closed','closed_timeout') NOT NULL DEFAULT 'pending',
    tunnel ENUM('wireguard','ssh_reverse') NOT NULL DEFAULT 'wireguard',
    endpoint VARCHAR(255) NULL,
    wg_client_private_key VARCHAR(64) NULL,
    wg_client_address VARCHAR(64) NULL,
    wg_server_public_key VARCHAR(64) NULL,
    wg_peer_allowed_ips VARCHAR(255) NULL,
    expires_at INT UNSIGNED NULL,
    last_activity_at TIMESTAMP NULL,
    close_reason VARCHAR(255) NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    closed_at TIMESTAMP NULL,
    UNIQUE KEY uq_ra_session (session_id),
    KEY idx_ra_sess_device (device_id, status),
    KEY idx_ra_sess_status (status, last_activity_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS remote_access_events (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(36) NULL,
    device_id VARCHAR(128) NOT NULL,
    actor_user_id INT UNSIGNED NULL,
    action VARCHAR(64) NOT NULL,
    reason VARCHAR(255) NULL,
    meta_json LONGTEXT NULL,
    client_ip VARCHAR(64) NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_ra_evt_device (device_id, created_at),
    KEY idx_ra_evt_session (session_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
