#![cfg(feature = "runtime-benchmarks")]

use super::*;

use crate::Pallet as GhostNetworks;
use frame_benchmarking::v1::{benchmarks, BenchmarkError};
use sp_runtime::Saturating;

use ghost_helpers::networks::{
    MAX_ENDPOINT_LEN, MAX_ENDPOINTS_LEN, MAX_GATEKEEPER_LEN,
    MAX_SELECTOR_LEN,
};

fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
    frame_system::Pallet::<T>::assert_last_event(generic_event.into());
}

fn prepare_network<T: Config>(
    n: u32,
    m: u32,
    k: u32,
) -> (T::NetworkId, NetworkData) {
    let chain_id: <T as module::Config>::NetworkId = Default::default();
    let chain_id = chain_id.saturating_add((n + m).into());

    let mut gatekeeper = sp_std::vec![];
    for i in 0..n {
        gatekeeper.push((i % 256) as u8);
    }

    let mut default_endpoints = sp_std::vec![];
    for _ in 0..(k as usize) {
        default_endpoints.push(sp_std::vec![0x69; m as usize]);
    }

    let network = ghost_helpers::networks::NetworkDataBuilder::default()
        .with_gatekeeper(gatekeeper)
    	.with_default_endpoints(default_endpoints)
        .with_selector(vec![1u8; 4])
        .with_network_type(NetworkType::Evm)
        .with_network_curve(NetworkCurve::Secp256k1)
        .with_rate_limit_delay(6)
        .with_finality_delay(69)
        .with_block_deviation(420)
        .with_incoming_share(0)
        .with_outgoing_share(0)
        .build();

    (chain_id, network)
}

fn create_network<T: Config>(
    chain_id: T::NetworkId,
    network: NetworkData,
) -> Result<Option<NetworkData>, BenchmarkError> {
    let prev_network = match GhostNetworks::<T>::get(&chain_id) {
        Some(net) => net,
        None => {
            let authority = T::RegisterOrigin::try_successful_origin()
                .map_err(|_| BenchmarkError::Weightless)?;
            GhostNetworks::<T>::register_network(
                authority,
                chain_id,
                network.clone(),
            )
            .map_err(|_| BenchmarkError::Weightless)?;
            network
        }
    };

    Ok(Some(prev_network))
}

benchmarks! {
    register_network {
        let i in 1 .. MAX_GATEKEEPER_LEN;
        let j in 1 .. MAX_ENDPOINT_LEN;
        let k in 1 .. MAX_ENDPOINTS_LEN;

        let (chain_id, network) = prepare_network::<T>(i, j, k);
        let authority = T::RegisterOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        assert_eq!(GhostNetworks::<T>::networks(chain_id), None);
        assert!(GhostNetworks::<T>::network_indexes().is_empty());
    }: _<T::RuntimeOrigin>(authority, chain_id, network.clone())
    verify {
        assert_last_event::<T>(Event::NetworkRegistered {chain_id: chain_id}.into());
        assert_eq!(GhostNetworks::<T>::networks(chain_id), Some(network));
        assert_eq!(GhostNetworks::<T>::network_indexes(), vec![chain_id]);
    }

    update_network_selector {
        let raw_selector = sp_std::vec![0x42; MAX_SELECTOR_LEN as usize];
        let selector = BoundedVec::<u8, ConstU32<MAX_SELECTOR_LEN>>::try_from(raw_selector)
        	.map_err(|_| BenchmarkError::Weightless)?;

        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, selector)
    verify {
        assert_last_event::<T>(Event::NetworkSelectorUpdated { chain_id }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    update_network_endpoint {
        let n in 1 .. MAX_ENDPOINT_LEN;
        let index = 0u32;
        let raw_endpoint = sp_std::vec![0x42; n as usize];
        let endpoint = BoundedVec::<u8, ConstU32<MAX_ENDPOINT_LEN>>::try_from(raw_endpoint)
        	.map_err(|_| BenchmarkError::Weightless)?;

        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, Some(index), Some(endpoint))
    verify {
        assert_last_event::<T>(Event::NetworkEndpointUpdated {chain_id, index }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    update_network_finality_delay {
        let delay = 1337;
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, delay)
    verify {
        assert_last_event::<T>(Event::NetworkFinalityDelayUpdated {
            chain_id, finality_delay: delay,
        }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    update_network_rate_limit_delay {
        let rate_limit = 1337;
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, rate_limit)
    verify {
        assert_last_event::<T>(Event::NetworkRateLimitDelayUpdated {
            chain_id, rate_limit_delay: rate_limit,
        }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    update_network_block_deviation {
        let block_deviation = 1337;
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, block_deviation)
    verify {
        assert_last_event::<T>(Event::NetworkBlockDeviationUpdated { chain_id, block_deviation }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    update_network_type {
        let network_type = NetworkType::Utxo;
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, network_type.clone())
    verify {
        assert_last_event::<T>(Event::NetworkTypeUpdated { chain_id, network_type }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);

    }

    update_network_curve {
        let network_curve = NetworkCurve::Ed25519;
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, network_curve)
    verify {
        assert_last_event::<T>(Event::NetworkCurveUpdated { chain_id, network_curve }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    update_network_gatekeeper {
        let mut raw_gatekeeper = b"0x".to_vec();
        for i in 0..40 { raw_gatekeeper.push(i + 1); }

        let gatekeeper =
        	BoundedVec::<u8, ConstU32<MAX_GATEKEEPER_LEN>>::try_from(raw_gatekeeper)
        		.map_err(|_| BenchmarkError::Weightless)?;

        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, gatekeeper)
    verify {
        assert_last_event::<T>(Event::NetworkGatekeeperUpdated { chain_id }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    update_incoming_network_share {
        let incoming_share = 1337;
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, incoming_share)
    verify {
        assert_last_event::<T>(Event::NetworkIncomingShareUpdated { chain_id, incoming_share }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
    }

    update_outgoing_network_share {
        let outgoing_share = 1337;
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::UpdateOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let prev_network = create_network::<T>(chain_id, network)?;
    }: _<T::RuntimeOrigin>(authority, chain_id, outgoing_share)
    verify {
        assert_last_event::<T>(Event::NetworkOutgoingShareUpdated { chain_id, outgoing_share }.into());
        assert_ne!(GhostNetworks::<T>::networks(chain_id), prev_network);
    }

    remove_network {
        let (chain_id, network) = prepare_network::<T>(1, 1, 1);
        let authority = T::RemoveOrigin::try_successful_origin()
            .map_err(|_| BenchmarkError::Weightless)?;
        let maybe_network = create_network::<T>(chain_id, network)?;
        assert_eq!(GhostNetworks::<T>::networks(chain_id), maybe_network);
        assert_eq!(GhostNetworks::<T>::network_indexes(), vec![chain_id]);
    }: _<T::RuntimeOrigin>(authority, chain_id)
    verify {
        assert_last_event::<T>(Event::NetworkRemoved { chain_id }.into());
        assert_eq!(GhostNetworks::<T>::networks(chain_id), None);
        assert!(GhostNetworks::<T>::network_indexes().is_empty());
    }

    impl_benchmark_test_suite!(GhostNetworks, crate::mock::ExtBuilder::build(), crate::mock::Test);
}
