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

use frame_system::EnsureRoot;
use frame_support::{
    derive_impl, parameter_types,
    traits::{ConstU32, ConstU64},
};
use crate as ghost_exodus;

use pallet_session::historical as pallet_session_historical;

use sp_runtime::{
    BuildStorage, curve::PiecewiseLinear, traits::ConvertInto,
    testing::{TestXt, UintAuthorityId},
};

use sp_staking::SessionIndex;

#[cfg(test)]
use ghost_helpers::networks::{NetworkInitiationBuilder, NetworkDataBuilder};

pub type MockedBalance = u64;
pub type MockedNetworkId = u64;
type Block = frame_system::mocking::MockBlock<Runtime>;

frame_support::construct_runtime!(
    pub enum Runtime {
        System: frame_system,
        Session: pallet_session,
        Historical: pallet_session_historical,
        Balances: pallet_balances,
        Networks: ghost_networks,
        Exodus: ghost_exodus,
    }
);

#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
    type Block = Block;
    type AccountData = pallet_balances::AccountData<MockedBalance>;
}

parameter_types! {
    pub static FixedAuthorities: Vec<u64> = vec![0, 1, 2, 3];
}

pub struct TestSessionManager;
impl pallet_session::SessionManager<u64> for TestSessionManager {
    fn new_session(_new_index: SessionIndex) -> Option<Vec<u64>> {
        Some(FixedAuthorities::get())
    }
    fn end_session(_: SessionIndex) {}
    fn start_session(_: SessionIndex) {}
}

impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
    fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
        Some(FixedAuthorities::get().iter().map(|l| (*l, *l)).collect())
    }
    fn end_session(_: SessionIndex) {}
    fn start_session(_: SessionIndex) {}
}

parameter_types! {
    pub const Period: u64 = 1;
    pub const Offset: u64 = 0;
}

impl pallet_session::Config for Runtime {
    type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
    type SessionManager =
        pallet_session::historical::NoteHistoricalRoot<Runtime, TestSessionManager>;
    type SessionHandler = (Exodus,);
    type ValidatorId = u64;
    type ValidatorIdOf = ConvertInto;
    type Keys = UintAuthorityId;
    type RuntimeEvent = RuntimeEvent;
    type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
    type WeightInfo = ();
}

impl pallet_session::historical::Config for Runtime {
    type FullIdentification = u64;
    type FullIdentificationOf = ConvertInto;
}

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

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

pallet_staking_reward_curve::build! {
    const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
        min_inflation: 0_006_000,
        max_inflation: 1_000_000,
        ideal_stake: 0_690_000,
        falloff: 0_050_000,
        max_piece_count: 100,
        test_precision: 0_005_000,
    );
}

parameter_types! {
    pub static ExistentialDeposit: u64 = 2;
    pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
    pub const HistoryDepth: u32 = 10;
    pub const EpochDuration: u64 = 80;
}

#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
    type ExistentialDeposit = ExistentialDeposit;
    type MaxReserves = ConstU32<2>;
    type AccountStore = System;
    type WeightInfo = ();
}

impl ghost_exodus::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
    type AuthorityId = UintAuthorityId;

    type ValidatorSet = Historical;
    type Currency = Balances;
    type NetworkDataHandler = Networks;
    type BlockNumberProvider = System;
    type DisabledValidators = Session;

    type UnsignedPriority = ConstU64<{ 1 << 20 }>;
    type UnsignedLongevity = ConstU64<1>;
    type MaxAuthorities = ConstU32<10>;
    type MaxAuthoritiesChunks = ConstU32<1>;

    type DkgRoundPeriod = ConstU64<100>;
    type RemovalLimit = ConstU32<20>;
    type MaxCursorLen = ConstU32<20>;

    type WeightInfo = ();
}

pub type Extrinsic<Call> = TestXt<Call, ()>;

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

#[allow(dead_code)]
pub fn new_test_ext_benchmarks() -> sp_io::TestExternalities {
    let t = frame_system::GenesisConfig::<Runtime>::default()
        .build_storage()
        .unwrap();

    sp_io::TestExternalities::new(t)
}

#[cfg(test)]
pub fn new_test_ext() -> (
    sp_io::TestExternalities,
    std::sync::Arc<parking_lot::RwLock<sp_core::offchain::testing::PoolState>>,
) {
    let mut t = frame_system::GenesisConfig::<Runtime>::default()
        .build_storage()
        .unwrap();

    let network_data = NetworkDataBuilder::default()
        .with_block_deviation(69)
        .build();

    let networks = vec![
        NetworkInitiationBuilder::<MockedNetworkId, u64>::default()
        	.with_network_id(31_337)
        	.with_gatekeeper_amount(0)
        	.with_network_data(network_data)
        	.build(),
    ];

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

    let mut ext = sp_io::TestExternalities::new(t);

    ext.execute_with(|| {
        for &id in FixedAuthorities::get().iter() {
            System::inc_providers(&id);
            assert_eq!(
                Session::set_keys(RuntimeOrigin::signed(id), id.into(), vec![],),
                Ok(())
            );
        }
    });

    let (offchain, _) = sp_core::offchain::testing::TestOffchainExt::with_offchain_db(ext.offchain_db());
    let (tx_pool, tx_pool_state) = sp_core::offchain::testing::TestTransactionPoolExt::new();

    ext.register_extension(sp_core::offchain::OffchainDbExt::new(offchain.clone()));
    ext.register_extension(sp_core::offchain::OffchainWorkerExt::new(offchain));
    ext.register_extension(sp_core::offchain::TransactionPoolExt::new(tx_pool));

    ext.execute_with(|| System::set_block_number(1));

    (ext, tx_pool_state)
}
