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

use crate::{self as ghost_weaver, *};
use frame_support::{
    derive_impl, parameter_types,
    traits::{ConstU32, ConstU64, Everything},
};
use frame_system::EnsureRoot;
use sp_core::{Pair, H256};
use sp_runtime::{
    testing::TestXt,
    traits::{BlakeTwo256, IdentityLookup},
    AccountId32, BuildStorage,
};

use ghost_helpers::networks::NetworkInitiationBuilder;

type Block = frame_system::mocking::MockBlock<TestRuntime>;
type Balance = u64;
type NetworkId = u32;

frame_support::construct_runtime!(
    pub enum TestRuntime {
        System: frame_system,
        Balances: pallet_balances,
        GhostNetworks: ghost_networks,
        GhostWeaver: ghost_weaver,
    }
);

#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for TestRuntime {
    type BaseCallFilter = Everything;
    type BlockWeights = ();
    type BlockLength = ();
    type DbWeight = ();
    type RuntimeOrigin = RuntimeOrigin;
    type RuntimeCall = RuntimeCall;
    type Nonce = u64;
    type Hash = H256;
    type Hashing = BlakeTwo256;
    type AccountId = AccountId32;
    type Lookup = IdentityLookup<Self::AccountId>;
    type Block = Block;
    type RuntimeEvent = RuntimeEvent;
    type BlockHashCount = ConstU64<250>;
    type Version = ();
    type PalletInfo = PalletInfo;
    type AccountData = pallet_balances::AccountData<Balance>;
    type OnNewAccount = ();
    type OnKilledAccount = ();
    type SystemWeightInfo = ();
    type SS58Prefix = ();
    type OnSetCode = ();
    type MaxConsumers = ConstU32<16>;
}

impl pallet_balances::Config for TestRuntime {
    type MaxLocks = ();
    type MaxReserves = ();
    type ReserveIdentifier = [u8; 8];
    type Balance = Balance;
    type RuntimeEvent = RuntimeEvent;
    type DustRemoval = ();
    type ExistentialDeposit = ConstU64<1>;
    type AccountStore = System;
    type WeightInfo = ();
    type FreezeIdentifier = ();
    type MaxFreezes = ();
    type RuntimeHoldReason = ();
    type RuntimeFreezeReason = ();
}

parameter_types! {
    pub const MaxNetworks: u32 = 5;
}

impl ghost_networks::Config for TestRuntime {
    type RuntimeEvent = RuntimeEvent;
    type Currency = Balances;
    type NetworkId = NetworkId;
    type RegisterOrigin = EnsureRoot<Self::AccountId>;
    type UpdateOrigin = EnsureRoot<Self::AccountId>;
    type RemoveOrigin = EnsureRoot<Self::AccountId>;
    type MaxNetworks = MaxNetworks;
    type WeightInfo = ();
}

#[allow(dead_code)]
pub type Extrinsic = TestXt<RuntimeCall, ()>;

impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for TestRuntime
where
    RuntimeCall: From<LocalCall>,
{
    type OverarchingCall = RuntimeCall;
    type Extrinsic = TestXt<RuntimeCall, ()>;
}

parameter_types! {
    pub const UnsignedPriority: u64 = 100;
    pub const WeavingDelay: u64 = 10;
    pub const AttestationDelay: u64 = 3;
}

impl ghost_weaver::Config for TestRuntime {
    type RuntimeEvent = RuntimeEvent;
    type AuthorityId = ghost_weaver::sr25519::AuthorityId;
    type Currency = Balances;
    type NetworkDataHandler = GhostNetworks;
    type BlockNumberProvider = System;
    type MaxAuthorities = ConstU32<20>;
    type MaxAuthoritiesChunks = ConstU32<1>;
    type WeavingDelay = WeavingDelay;
    type AttestationDelay = AttestationDelay;
    type UnsignedPriority = UnsignedPriority;
    type WeightInfo = ();
}

#[allow(dead_code)]
pub fn new_test_ext(
    authorities: Vec<sr25519::AuthorityPair>,
    networks_raw: Vec<(NetworkId, NetworkData, Balance)>,
) -> sp_io::TestExternalities {
    let mut t = frame_system::GenesisConfig::<TestRuntime>::default()
        .build_storage()
        .unwrap();

    let genesis_authorities = authorities
        .iter()
        .enumerate()
        .map(|(i, pair)| {
            let mut id_bytes = [0u8; 32];
            let id_u64 = (i + 1) as u64;
            id_bytes[0..8].copy_from_slice(&id_u64.to_le_bytes());

            let account_id = AccountId32::from(id_bytes);
            (account_id, pair.public().clone())
        })
        .collect::<Vec<_>>();

    let networks = networks_raw
        .into_iter()
        .map(|(network_id, network_data, amount)| {
            NetworkInitiationBuilder::default()
                .with_network_id(network_id)
                .with_network_data(network_data)
                .with_gatekeeper_amount(amount)
                .build()
        })
        .collect::<Vec<_>>();

    ghost_networks::GenesisConfig::<TestRuntime> { networks }
        .assimilate_storage(&mut t)
        .unwrap();

    ghost_weaver::GenesisConfig::<TestRuntime> {
        authorities: genesis_authorities,
        loom_states: vec![],
    }
    .assimilate_storage(&mut t)
    .unwrap();

    let keystore = sp_keystore::testing::MemoryKeystore::new();
    let mut ext = sp_io::TestExternalities::new(t);

    ext.register_extension(sp_keystore::KeystoreExt::new(keystore));
    ext.execute_with(|| System::set_block_number(1));

    ext
}
