use anyhow::bail;
use serde::{Deserialize, Serialize};
use tokio_postgres::Row;

#[derive(Serialize, Deserialize, Debug)]
pub struct Currency {
    pub id: CurrencyId,
    pub name: String,
}

impl TryFrom<&Row> for Currency {
    type Error = crate::Error;

    fn try_from(value: &Row) -> Result<Self, Self::Error> {
        let id: i64 = value.try_get("id")?;
        let name: String = value.try_get("name")?;

        Ok(Currency {
            id: id.try_into()?,
            name: name,
        })
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub enum CurrencyId {
    USD = 1,
    None = 2,
}

impl TryFrom<i64> for CurrencyId {
    type Error = anyhow::Error;

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        let id = match value {
            1 => CurrencyId::USD,
            2 => CurrencyId::None,
            _ => bail!("couldn't match value {value} to currency id"),
        };

        Ok(id)
    }
}

impl CurrencyId {
    pub fn get_name_from_id(&self) -> String {
        let v = match self {
            CurrencyId::USD => "USD",
            CurrencyId::None => "",
        };
        v.to_string()
    }
}
