CREATE TABLE IF NOT EXISTS vehicle_reconciliation_run (
    run_id VARCHAR(64) NOT NULL PRIMARY KEY,
    status VARCHAR(24) NOT NULL,
    detected_count INT UNSIGNED NOT NULL DEFAULT 0,
    new_count INT UNSIGNED NOT NULL DEFAULT 0,
    active_count INT UNSIGNED NOT NULL DEFAULT 0,
    recovered_count INT UNSIGNED NOT NULL DEFAULT 0,
    rule_counts_json JSON NOT NULL,
    error_message VARCHAR(512) NOT NULL DEFAULT '',
    started_at DATETIME(3) NOT NULL,
    finished_at DATETIME(3) NOT NULL,
    INDEX idx_reconciliation_run_finished (finished_at, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS vehicle_reconciliation_issue (
    id VARCHAR(64) NOT NULL PRIMARY KEY,
    fingerprint CHAR(64) NOT NULL,
    rule_code VARCHAR(64) NOT NULL,
    category VARCHAR(32) NOT NULL,
    severity VARCHAR(16) NOT NULL,
    status VARCHAR(32) NOT NULL,
    vin VARCHAR(64) NOT NULL DEFAULT '',
    plate VARCHAR(64) NOT NULL DEFAULT '',
    protocol_a VARCHAR(32) NOT NULL DEFAULT '',
    protocol_b VARCHAR(32) NOT NULL DEFAULT '',
    title VARCHAR(160) NOT NULL,
    summary VARCHAR(500) NOT NULL,
    evidence_json JSON NOT NULL,
    first_seen_at DATETIME(3) NOT NULL,
    last_seen_at DATETIME(3) NOT NULL,
    occurrence_count BIGINT UNSIGNED NOT NULL DEFAULT 1,
    recovered_at DATETIME(3) NULL,
    resolution_note VARCHAR(500) NOT NULL DEFAULT '',
    resolved_by VARCHAR(128) NOT NULL DEFAULT '',
    version INT UNSIGNED NOT NULL DEFAULT 1,
    created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    UNIQUE KEY uk_reconciliation_fingerprint (fingerprint),
    INDEX idx_reconciliation_status (status, severity, last_seen_at),
    INDEX idx_reconciliation_rule (rule_code, last_seen_at),
    INDEX idx_reconciliation_vehicle (vin, last_seen_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS vehicle_reconciliation_action (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    issue_id VARCHAR(64) NOT NULL,
    action VARCHAR(32) NOT NULL,
    from_status VARCHAR(32) NOT NULL,
    to_status VARCHAR(32) NOT NULL,
    actor VARCHAR(128) NOT NULL,
    note VARCHAR(500) NOT NULL DEFAULT '',
    created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    INDEX idx_reconciliation_action_issue (issue_id, created_at),
    INDEX idx_reconciliation_action_actor (actor, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
