use bls::{SecretKey, Signature};
use context_deserialize::context_deserialize;
use serde::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode};
use tree_hash_derive::TreeHash;

use crate::{
    core::{ChainSpec, Domain, EthSpec, Hash256, SignedRoot},
    fork::{Fork, ForkName},
    sync_committee::{ContributionAndProof, SyncCommitteeContribution, SyncSelectionProof},
};

/// A Validators signed contribution proof to publish on the `sync_committee_contribution_and_proof`
/// gossipsub topic.
#[cfg_attr(
    feature = "arbitrary",
    derive(arbitrary::Arbitrary),
    arbitrary(bound = "E: EthSpec")
)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode, TreeHash)]
#[serde(bound = "E: EthSpec")]
#[context_deserialize(ForkName)]
pub struct SignedContributionAndProof<E: EthSpec> {
    /// The `ContributionAndProof` that was signed.
    pub message: ContributionAndProof<E>,
    /// The validator's signature of `message`.
    pub signature: Signature,
}

impl<E: EthSpec> SignedContributionAndProof<E> {
    /// Produces a new `SignedContributionAndProof` with a `selection_proof` generated by signing
    /// `aggregate.data.slot` with `secret_key`.
    ///
    /// If `selection_proof.is_none()` it will be computed locally.
    pub fn from_aggregate(
        aggregator_index: u64,
        contribution: SyncCommitteeContribution<E>,
        selection_proof: Option<SyncSelectionProof>,
        secret_key: &SecretKey,
        fork: &Fork,
        genesis_validators_root: Hash256,
        spec: &ChainSpec,
    ) -> Self {
        let message = ContributionAndProof::from_aggregate(
            aggregator_index,
            contribution,
            selection_proof,
            secret_key,
            fork,
            genesis_validators_root,
            spec,
        );

        let epoch = message.contribution.slot.epoch(E::slots_per_epoch());
        let domain = spec.get_domain(
            epoch,
            Domain::ContributionAndProof,
            fork,
            genesis_validators_root,
        );
        let signing_message = message.signing_root(domain);

        SignedContributionAndProof {
            message,
            signature: secret_key.sign(signing_message),
        }
    }
}
