use alloc::string::String;

use miden_protocol::account::StorageSlotName;
use miden_protocol::errors::{AccountError, TokenSymbolError};
use thiserror::Error;

use crate::account::access::Ownable2StepError;
use crate::utils::FixedWidthStringError;

mod fungible;
mod token_metadata;

pub use fungible::{FungibleFaucet, FungibleFaucetBuilder, create_fungible_faucet};
pub use token_metadata::{Description, ExternalLink, LogoURI, TokenMetadata, TokenName};

// TOKEN METADATA ERROR
// ================================================================================================

/// Errors raised when parsing token metadata from storage.
#[derive(Debug, Error)]
pub enum TokenMetadataError {
    #[error("failed to retrieve storage slot with name {slot_name}")]
    StorageLookupFailed {
        slot_name: StorageSlotName,
        source: AccountError,
    },
    #[error("invalid string data in field '{field}'")]
    InvalidStringField {
        field: &'static str,
        #[source]
        source: FixedWidthStringError,
    },
    #[error("mutability flag at index {index} has invalid value {value}: must be 0 or 1")]
    InvalidMutabilityFlag { index: usize, value: u64 },
    #[error("storage slot name mismatch: expected {expected}, got {actual}")]
    SlotNameMismatch {
        expected: StorageSlotName,
        actual: StorageSlotName,
    },
    #[error("invalid token symbol")]
    InvalidTokenSymbol(#[source] TokenSymbolError),
}

// FUNGIBLE FAUCET ERROR
// ================================================================================================

/// Basic fungible faucet related errors.
#[derive(Debug, Error)]
pub enum FungibleFaucetError {
    #[error("faucet metadata decimals is {actual} which exceeds max value of {max}")]
    TooManyDecimals { actual: u64, max: u8 },
    #[error("faucet metadata max supply is {actual} which exceeds max value of {max}")]
    MaxSupplyTooLarge { actual: u64, max: u64 },
    #[error("token supply {token_supply} exceeds max_supply {max_supply}")]
    TokenSupplyExceedsMaxSupply { token_supply: u64, max_supply: u64 },
    #[error(
        "account interface does not have the procedures of the basic fungible faucet component"
    )]
    MissingFungibleFaucetInterface,
    #[error("unsupported authentication method: {0}")]
    UnsupportedAuthMethod(String),
    #[error("AccessControl::AuthControlled is incompatible with the chosen auth method: {0}")]
    IncompatibleAuthControlledAuth(String),
    #[error("unsupported combination of AccessControl and AuthMethod: {0}")]
    UnsupportedAccessControlAuthCombination(String),
    #[error("account creation failed")]
    AccountError(#[source] AccountError),
    #[error("account is not a fungible faucet account")]
    NotAFungibleFaucetAccount,
    #[error("failed to read ownership data from storage")]
    OwnershipError(#[source] Ownable2StepError),
    #[error(transparent)]
    TokenMetadata(#[from] TokenMetadataError),
}
