// SPDX-FileCopyrightText: Heiko Schaefer <heiko@schaefer.name>
// SPDX-License-Identifier: MIT OR Apache-2.0

#![allow(clippy::expect_used)]

use std::path::PathBuf;

use rpgpie::merge::CertificateInfo;

#[allow(clippy::panic)]
fn merge_test(orig: &str, updates: &[&str], expected: &str) {
    let CertificateInfo::Cert(orig) =
        CertificateInfo::from_file(&PathBuf::from(orig)).expect("load")
    else {
        panic!("unexpected CertificateInfo variant");
    };

    let updates: Vec<_> = updates
        .iter()
        .map(|p| CertificateInfo::from_file(&PathBuf::from(p)).expect("certificate info"))
        .collect();

    let mut merged = orig;
    merged.merge(updates);

    let CertificateInfo::Cert(expected) =
        CertificateInfo::from_file(&PathBuf::from(expected)).expect("load")
    else {
        panic!("unexpected CertificateInfo variant");
    };

    assert_eq!(merged, expected);
}

#[test]
fn merge_global_directory() {
    merge_test(
        "tests/merge/updates/50bb6ffc9719dfd2bebb04c69710b89bca57ad7c.orig",
        &[
            "tests/merge/updates/50bb6ffc9719dfd2bebb04c69710b89bca57ad7c.koo",
            "tests/merge/updates/50bb6ffc9719dfd2bebb04c69710b89bca57ad7c.pgpkeys",
            "tests/merge/updates/50bb6ffc9719dfd2bebb04c69710b89bca57ad7c.ubuntu",
        ],
        "tests/merge/updates/50bb6ffc9719dfd2bebb04c69710b89bca57ad7c.expected",
    );
}

#[test]
fn merge_unusual_subkeys() {
    // this certificate has secp256k1, brainpool256 subkeys

    merge_test(
        "tests/merge/updates/9f840f3da1f1b4c77ecb6553d0c3ad9cf0b605d3.orig",
        &[
            "tests/merge/updates/9f840f3da1f1b4c77ecb6553d0c3ad9cf0b605d3.pgpkeys",
            "tests/merge/updates/9f840f3da1f1b4c77ecb6553d0c3ad9cf0b605d3.ubuntu",
        ],
        "tests/merge/updates/9f840f3da1f1b4c77ecb6553d0c3ad9cf0b605d3.expected",
    );
}

#[test]
fn merge_unhashed_subpackets() {
    // merging requires unifying unhashed subpackets between signatures

    merge_test(
        "tests/merge/updates/02fd1c7a934e614545849f19a6234074498e9cee.orig",
        &[
            "tests/merge/updates/02fd1c7a934e614545849f19a6234074498e9cee.pgpkeys",
            "tests/merge/updates/02fd1c7a934e614545849f19a6234074498e9cee.ubuntu",
        ],
        "tests/merge/updates/02fd1c7a934e614545849f19a6234074498e9cee.expected",
    );
}
