use crate::market::{CandidMarketIdentifier, MarketIdentifier};
use crate::{
    number::Ex3Uint, AssetAmount, BlockHeight, CandidAssetAmount, CandidBlockHeight,
    CandidSpotMarketId, CandidWalletRegisterId, SpotMarketId, WalletRegisterId,
};
use candid::{CandidType, Deserialize, Nat};
use ex3_serde::bincode;
use ic_stable_structures::{storable::Bound, Storable};
use serde::Serialize;

/// Represents a spot market with its identifier, trading settings, fee, fee recipient, and optional royalty.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct SpotMarket {
    /// Spot market identifier
    pub identifier: MarketIdentifier,

    /// Market trading settings
    pub trading_settings: SpotMarketTradingSettings,

    /// Trading fee
    pub fee: SpotMarketTradingFee,

    /// Trading fee recipient
    pub fee_to: WalletRegisterId,

    /// Optional royalty fee
    pub royalty: Option<SpotMarketRoyalty>,
}

/// Represents a registered spot market with its ID, market details, and registered height.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct RegisteredSpotMarket {
    /// Spot market ID
    pub id: SpotMarketId,

    /// Spot market details
    pub market: SpotMarket,

    /// Registered block height
    pub registered_height: BlockHeight,
}

impl Storable for RegisteredSpotMarket {
    fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
        bincode::serialize(self).unwrap().into()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        bincode::deserialize(bytes.as_ref()).unwrap()
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: 384,
        is_fixed_size: false,
    };
}

/// Represents the trading fee structure for a spot market.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SpotMarketTradingFee {
    /// Limit order taker fee
    /// Swap fee is the same as limit order taker fee
    pub taker_fee: Ex3Uint,

    /// Limit order maker fee
    pub maker_fee: Ex3Uint,

    /// AMM V2 fee taking ratio
    /// # Range
    /// 0 ~ 100
    /// # Example
    /// * 0: 0%
    /// * 100: 100%
    /// # Note
    /// This value is used for AMM V2
    pub amm_v2_fee_taking_ratio: Ex3Uint,

    /// Fee decimal for
    /// * `taker_fee` & `maker_fee` & `amm_v2_fee_taking_ratio`
    pub fee_decimal: u8,
}

impl Storable for SpotMarketTradingFee {
    fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
        bincode::serialize(self).unwrap().into()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        bincode::deserialize(bytes.as_ref()).unwrap()
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: 97,
        is_fixed_size: false,
    };
}

/// Represents the royalty fee structure for a spot market.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SpotMarketRoyalty {
    /// Royalty fee for buyer
    pub buyer_fee: Ex3Uint,

    /// Royalty fee for seller
    pub seller_fee: Ex3Uint,

    /// Fee decimal for
    /// * `buyer_fee` & `seller_fee`
    pub fee_decimal: u8,
}

impl Storable for SpotMarketRoyalty {
    fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
        bincode::serialize(self).unwrap().into()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        bincode::deserialize(bytes.as_ref()).unwrap()
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: 65,
        is_fixed_size: false,
    };
}

/// Represents the orderbook price limitation.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SpotOrderPriceLimitation {
    /// Orderbook bidding price rate cap
    pub bid_price_rate_cap: Ex3Uint,
    /// Orderbook asking price rate floor
    pub ask_price_rate_floor: Ex3Uint,
    /// Price rate decimal
    pub rate_decimal: u8,
}

/// Represents the trading settings for a spot market.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SpotMarketTradingSettings {
    /// Maximum decimal places for price
    /// Orderbook price decimal & swap price decimal use this value
    pub price_max_decimal: u8,

    /// Maximum decimal places for volume
    /// Orderbook volume decimal & swap volume decimal use this value
    /// Note: volume means base asset quantity
    pub volume_max_decimal: u8,

    /// Minimum order amount
    /// Orderbook minimum order amount & swap minimum order amount use this value
    /// Note: amount means quota asset quantity
    pub min_order_amount: AssetAmount,

    /// Minimum order volume
    /// Orderbook minimum order volume & swap minimum order volume use this value
    /// Note: volume means base asset quantity
    pub min_order_volume: AssetAmount,

    /// Price limitation
    pub price_limitation: SpotOrderPriceLimitation,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotMarketTradingFee {
    /// Limit order taker fee
    /// Swap fee is the same as limit order taker fee
    pub taker_fee: Nat,

    /// Orderbook maker fee
    pub maker_fee: Nat,

    /// AMM V2 fee taking ratio
    /// # Range
    /// 0 ~ 100
    /// # Example
    /// * 0: 0%
    /// * 100: 100%
    /// # Note
    /// This value is used for AMM V2
    pub amm_v2_fee_taking_ratio: Nat,

    /// Fee decimal for
    /// * `taker_fee` & `maker_fee` & `amm_v2_fee_taking_ratio`
    pub fee_decimal: u8,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotMarketRoyalty {
    /// Royalty fee for buyer
    pub buyer_fee: Nat,

    /// Royalty fee for seller
    pub seller_fee: Nat,

    /// Fee decimal for
    /// * `taker_fee` & `maker_fee`
    pub fee_decimal: u8,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotOrderPriceLimitation {
    /// Orderbook biding price rate cap
    pub bid_price_rate_cap: Nat,
    /// Orderbook asking price rate floor
    pub ask_price_rate_floor: Nat,
    /// Price rate decimal
    pub rate_decimal: u8,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotMarketTradingSettings {
    /// Price max decimal
    /// Orderbook price decimal & swap price decimal use this value
    pub price_max_decimal: u8,

    /// Volume max decimal
    /// Orderbook volume decimal & swap volume decimal use this value
    /// Note: volume means base asset quantity
    pub volume_max_decimal: u8,

    /// Min order amount
    /// Orderbook min order amount & swap min order amount use this value
    /// Note: amount means quota asset quantity
    pub min_order_amount: CandidAssetAmount,

    /// Min order volume
    /// Orderbook min order volume & swap min order volume use this value
    /// Note: volume means base asset quantity
    pub min_order_volume: CandidAssetAmount,

    /// Price limitation
    pub price_limitation: CandidSpotOrderPriceLimitation,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotMarket {
    /// Identifier
    pub identifier: CandidMarketIdentifier,

    /// Market trading settings
    pub trading_settings: CandidSpotMarketTradingSettings,

    /// Market trading fee
    pub fee: CandidSpotMarketTradingFee,

    /// Market fee to
    /// Trading fee to
    pub fee_to: CandidWalletRegisterId,

    /// Market royalty
    pub royalty: Option<CandidSpotMarketRoyalty>,
}

#[derive(CandidType, Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CandidRegisteredSpotMarket {
    /// Spot market id
    pub id: CandidSpotMarketId,

    /// Spot market
    pub market: CandidSpotMarket,

    /// Registered height
    pub registered_height: CandidBlockHeight,
}

impl From<CandidSpotMarketTradingFee> for SpotMarketTradingFee {
    fn from(candid_market_trading_fee: CandidSpotMarketTradingFee) -> Self {
        SpotMarketTradingFee {
            taker_fee: candid_market_trading_fee.taker_fee.into(),
            maker_fee: candid_market_trading_fee.maker_fee.into(),
            amm_v2_fee_taking_ratio: candid_market_trading_fee.amm_v2_fee_taking_ratio.into(),
            fee_decimal: candid_market_trading_fee.fee_decimal,
        }
    }
}

impl From<SpotMarketTradingFee> for CandidSpotMarketTradingFee {
    fn from(market_trading_fee: SpotMarketTradingFee) -> Self {
        CandidSpotMarketTradingFee {
            taker_fee: market_trading_fee.taker_fee.into(),
            maker_fee: market_trading_fee.maker_fee.into(),
            amm_v2_fee_taking_ratio: market_trading_fee.amm_v2_fee_taking_ratio.into(),
            fee_decimal: market_trading_fee.fee_decimal,
        }
    }
}

impl From<CandidSpotMarketRoyalty> for SpotMarketRoyalty {
    fn from(candid_market_royalty: CandidSpotMarketRoyalty) -> Self {
        SpotMarketRoyalty {
            buyer_fee: candid_market_royalty.buyer_fee.into(),
            seller_fee: candid_market_royalty.seller_fee.into(),
            fee_decimal: candid_market_royalty.fee_decimal,
        }
    }
}

impl From<CandidSpotOrderPriceLimitation> for SpotOrderPriceLimitation {
    fn from(candid_order_price_limitation: CandidSpotOrderPriceLimitation) -> Self {
        SpotOrderPriceLimitation {
            bid_price_rate_cap: candid_order_price_limitation.bid_price_rate_cap.into(),
            ask_price_rate_floor: candid_order_price_limitation.ask_price_rate_floor.into(),
            rate_decimal: candid_order_price_limitation.rate_decimal,
        }
    }
}

impl From<SpotMarketRoyalty> for CandidSpotMarketRoyalty {
    fn from(market_royalty: SpotMarketRoyalty) -> Self {
        CandidSpotMarketRoyalty {
            buyer_fee: market_royalty.buyer_fee.into(),
            seller_fee: market_royalty.seller_fee.into(),
            fee_decimal: market_royalty.fee_decimal,
        }
    }
}

impl From<SpotOrderPriceLimitation> for CandidSpotOrderPriceLimitation {
    fn from(order_price_limitation: SpotOrderPriceLimitation) -> Self {
        CandidSpotOrderPriceLimitation {
            bid_price_rate_cap: order_price_limitation.bid_price_rate_cap.into(),
            ask_price_rate_floor: order_price_limitation.ask_price_rate_floor.into(),
            rate_decimal: order_price_limitation.rate_decimal,
        }
    }
}

impl From<CandidSpotMarketTradingSettings> for SpotMarketTradingSettings {
    fn from(candid_market_trading_settings: CandidSpotMarketTradingSettings) -> Self {
        SpotMarketTradingSettings {
            price_max_decimal: candid_market_trading_settings.price_max_decimal,
            volume_max_decimal: candid_market_trading_settings.volume_max_decimal,
            min_order_amount: candid_market_trading_settings.min_order_amount.into(),
            min_order_volume: candid_market_trading_settings.min_order_volume.into(),
            price_limitation: candid_market_trading_settings.price_limitation.into(),
        }
    }
}

impl From<SpotMarketTradingSettings> for CandidSpotMarketTradingSettings {
    fn from(market_trading_settings: SpotMarketTradingSettings) -> Self {
        CandidSpotMarketTradingSettings {
            price_max_decimal: market_trading_settings.price_max_decimal,
            volume_max_decimal: market_trading_settings.volume_max_decimal,
            min_order_amount: market_trading_settings.min_order_amount.into(),
            min_order_volume: market_trading_settings.min_order_volume.into(),
            price_limitation: market_trading_settings.price_limitation.into(),
        }
    }
}

impl From<CandidSpotMarket> for SpotMarket {
    fn from(candid_market: CandidSpotMarket) -> Self {
        SpotMarket {
            identifier: candid_market.identifier.into(),
            trading_settings: candid_market.trading_settings.into(),
            fee: candid_market.fee.into(),
            fee_to: candid_market.fee_to.into(),
            royalty: candid_market.royalty.map(|royalty| royalty.into()),
        }
    }
}

impl From<SpotMarket> for CandidSpotMarket {
    fn from(market: SpotMarket) -> Self {
        CandidSpotMarket {
            identifier: market.identifier.into(),
            trading_settings: market.trading_settings.into(),
            fee: market.fee.into(),
            fee_to: market.fee_to.into(),
            royalty: market.royalty.map(|royalty| royalty.into()),
        }
    }
}

impl From<RegisteredSpotMarket> for CandidRegisteredSpotMarket {
    fn from(registered_spot_market: RegisteredSpotMarket) -> Self {
        CandidRegisteredSpotMarket {
            id: registered_spot_market.id.into(),
            market: registered_spot_market.market.into(),
            registered_height: registered_spot_market.registered_height.into(),
        }
    }
}

impl From<CandidRegisteredSpotMarket> for RegisteredSpotMarket {
    fn from(candid_registered_spot_market: CandidRegisteredSpotMarket) -> Self {
        RegisteredSpotMarket {
            id: candid_registered_spot_market.id.into(),
            market: candid_registered_spot_market.market.into(),
            registered_height: candid_registered_spot_market.registered_height.into(),
        }
    }
}
