-- PS_Launcher schema v1
-- À jouer dans la base MySQL OVH créée via le manager.
-- Charset : utf8mb4 obligatoire (ownership names accentués, JSON details).

CREATE TABLE IF NOT EXISTS licenses (
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    license_key VARCHAR(64) NOT NULL UNIQUE,
    owner_name VARCHAR(255) NOT NULL,
    issued_at DATETIME NOT NULL,
    download_entitlement_until DATETIME NOT NULL,
    max_machines INT UNSIGNED NOT NULL DEFAULT 1,
    revoked_at DATETIME NULL,
    notes TEXT NULL,
    INDEX idx_license_key (license_key),
    INDEX idx_revoked (revoked_at),
    INDEX idx_entitlement (download_entitlement_until)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS license_machines (
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    license_id BIGINT UNSIGNED NOT NULL,
    machine_id VARCHAR(128) NOT NULL,
    machine_label VARCHAR(255) NULL,
    first_seen DATETIME NOT NULL,
    last_seen DATETIME NOT NULL,
    UNIQUE KEY uk_license_machine (license_id, machine_id),
    INDEX idx_last_seen (last_seen),
    CONSTRAINT fk_machine_license FOREIGN KEY (license_id)
        REFERENCES licenses(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_limit (
    ip VARCHAR(45) PRIMARY KEY,
    window_start DATETIME NOT NULL,
    counter INT UNSIGNED NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS audit_log (
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    ts DATETIME NOT NULL,
    license_id BIGINT UNSIGNED NULL,
    ip VARCHAR(45) NULL,
    event VARCHAR(64) NOT NULL,
    detail JSON NULL,
    INDEX idx_ts (ts),
    INDEX idx_event (event),
    CONSTRAINT fk_audit_license FOREIGN KEY (license_id)
        REFERENCES licenses(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
