-- MSIN API ChronoTrack — Phase 1 : tables config, mapping, token, logs
-- Prérequis : aucun
-- Idempotent : oui (CREATE IF NOT EXISTS)
--
-- IMPORTANT — sélectionner la base AVANT d'exécuter (sinon erreur 1046).
-- Décommenter UNE ligne USE ci-dessous selon l'environnement :
--
-- USE devinscription_preprod;
-- USE devinscription_prod;
-- USE ms1incription_preprod;
-- USE ms1incription_prod;
CREATE TABLE IF NOT EXISTS api_chronotrack_config (
    eve_id INT UNSIGNED NOT NULL,
    ct_event_id BIGINT UNSIGNED NOT NULL,
    ct_event_name VARCHAR(255) NOT NULL DEFAULT '',
    ct_event_date DATETIME NULL DEFAULT NULL,
    sync_status ENUM('lie', 'actif', 'ferme') NOT NULL DEFAULT 'lie',
    linked_at DATETIME NULL DEFAULT NULL,
    linked_by_usa_id INT UNSIGNED NULL DEFAULT NULL,
    activated_at DATETIME NULL DEFAULT NULL,
    closed_at DATETIME NULL DEFAULT NULL,
    closed_by_usa_id INT UNSIGNED NULL DEFAULT NULL,
    updated_at DATETIME NOT NULL,
    PRIMARY KEY (eve_id),
    KEY idx_ct_event (ct_event_id),
    KEY idx_sync_status (sync_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS api_chronotrack_race_map (
    map_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    eve_id INT UNSIGNED NOT NULL,
    epr_id INT UNSIGNED NOT NULL,
    ct_race_id BIGINT UNSIGNED NOT NULL,
    ct_race_name VARCHAR(255) NOT NULL DEFAULT '',
    updated_at DATETIME NOT NULL,
    PRIMARY KEY (map_id),
    UNIQUE KEY uq_eve_epr (eve_id, epr_id),
    KEY idx_eve_id (eve_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS api_chronotrack_token (
    token_key VARCHAR(32) NOT NULL DEFAULT 'default',
    access_token TEXT NULL,
    refresh_token TEXT NULL,
    expires_at DATETIME NULL DEFAULT NULL,
    updated_at DATETIME NOT NULL,
    PRIMARY KEY (token_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS api_chronotrack_sync_log (
    log_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    eve_id INT UNSIGNED NOT NULL,
    par_id INT UNSIGNED NULL DEFAULT NULL,
    action VARCHAR(32) NOT NULL DEFAULT '',
    status ENUM('ok', 'error', 'pending') NOT NULL DEFAULT 'pending',
    message TEXT NULL,
    created_at DATETIME NOT NULL,
    PRIMARY KEY (log_id),
    KEY idx_eve_created (eve_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
