//! This code was AUTOGENERATED using the Codama library.
use carbon_core::{
    account::AccountMetadata,
    postgres::{
        metadata::AccountRowMetadata,
        primitives::{Pubkey, U16, U32, U64, U8},
    },
};

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct AmmConfigRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub bump: U8,
    pub index: U16,
    pub owner: Pubkey,
    pub protocol_fee_rate: U32,
    pub trade_fee_rate: U32,
    pub tick_spacing: U16,
    pub fund_fee_rate: U32,
    pub padding_u32: U32,
    pub fund_owner: Pubkey,
    pub padding: Vec<U64>,
}

impl AmmConfigRow {
    pub fn from_parts(
        source: crate::accounts::amm_config::AmmConfig,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            bump: source.bump.into(),
            index: source.index.into(),
            owner: source.owner.into(),
            protocol_fee_rate: source.protocol_fee_rate.into(),
            trade_fee_rate: source.trade_fee_rate.into(),
            tick_spacing: source.tick_spacing.into(),
            fund_fee_rate: source.fund_fee_rate.into(),
            padding_u32: source.padding_u32.into(),
            fund_owner: source.fund_owner.into(),
            padding: source
                .padding
                .into_iter()
                .map(|element| element.into())
                .collect(),
        }
    }
}

impl TryFrom<AmmConfigRow> for crate::accounts::amm_config::AmmConfig {
    type Error = carbon_core::error::Error;
    fn try_from(source: AmmConfigRow) -> Result<Self, Self::Error> {
        Ok(Self {
            bump: source.bump.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            index: source.index.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            owner: *source.owner,
            protocol_fee_rate: source.protocol_fee_rate.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            trade_fee_rate: source.trade_fee_rate.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            tick_spacing: source.tick_spacing.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            fund_fee_rate: source.fund_fee_rate.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            padding_u32: source.padding_u32.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            fund_owner: *source.fund_owner,
            padding: source
                .padding
                .into_iter()
                .map(|element| Ok(*element))
                .collect::<Result<Vec<_>, carbon_core::error::Error>>()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to collect array elements".to_string(),
                    )
                })?
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert array element to primitive".to_string(),
                    )
                })?,
        })
    }
}

impl carbon_core::postgres::operations::Table for crate::accounts::amm_config::AmmConfig {
    fn table() -> &'static str {
        "amm_config_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "bump",
            "index",
            "owner",
            "protocol_fee_rate",
            "trade_fee_rate",
            "tick_spacing",
            "fund_fee_rate",
            "padding_u32",
            "fund_owner",
            "padding",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for AmmConfigRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO amm_config_account (
                "bump",
                "index",
                "owner",
                "protocol_fee_rate",
                "trade_fee_rate",
                "tick_spacing",
                "fund_fee_rate",
                "padding_u32",
                "fund_owner",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12
            )"#,
        )
        .bind(self.bump)
        .bind(self.index)
        .bind(self.owner)
        .bind(self.protocol_fee_rate)
        .bind(self.trade_fee_rate)
        .bind(self.tick_spacing)
        .bind(self.fund_fee_rate)
        .bind(self.padding_u32)
        .bind(self.fund_owner)
        .bind(&self.padding)
        .bind(self.account_metadata.pubkey)
        .bind(&self.account_metadata.slot)
        .execute(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Upsert for AmmConfigRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO amm_config_account (
                "bump",
                "index",
                "owner",
                "protocol_fee_rate",
                "trade_fee_rate",
                "tick_spacing",
                "fund_fee_rate",
                "padding_u32",
                "fund_owner",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "bump" = EXCLUDED."bump",
                "index" = EXCLUDED."index",
                "owner" = EXCLUDED."owner",
                "protocol_fee_rate" = EXCLUDED."protocol_fee_rate",
                "trade_fee_rate" = EXCLUDED."trade_fee_rate",
                "tick_spacing" = EXCLUDED."tick_spacing",
                "fund_fee_rate" = EXCLUDED."fund_fee_rate",
                "padding_u32" = EXCLUDED."padding_u32",
                "fund_owner" = EXCLUDED."fund_owner",
                "padding" = EXCLUDED."padding",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(self.bump)
        .bind(self.index)
        .bind(self.owner)
        .bind(self.protocol_fee_rate)
        .bind(self.trade_fee_rate)
        .bind(self.tick_spacing)
        .bind(self.fund_fee_rate)
        .bind(self.padding_u32)
        .bind(self.fund_owner)
        .bind(&self.padding)
        .bind(self.account_metadata.pubkey)
        .bind(&self.account_metadata.slot)
        .execute(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Delete for AmmConfigRow {
    type Key = carbon_core::postgres::primitives::Pubkey;

    async fn delete(key: Self::Key, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"DELETE FROM amm_config_account WHERE
                __pubkey = $1
            "#,
        )
        .bind(key)
        .execute(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Lookup for AmmConfigRow {
    type Key = carbon_core::postgres::primitives::Pubkey;

    async fn lookup(
        key: Self::Key,
        pool: &sqlx::PgPool,
    ) -> carbon_core::error::CarbonResult<Option<Self>> {
        let row = sqlx::query_as(
            r#"SELECT * FROM amm_config_account WHERE
                __pubkey = $1
            "#,
        )
        .bind(key)
        .fetch_optional(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(row)
    }
}

pub struct AmmConfigMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for AmmConfigMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS amm_config_account (
                -- Account data
                "bump" INT2 NOT NULL,
                "index" INT4 NOT NULL,
                "owner" BYTEA NOT NULL,
                "protocol_fee_rate" INT8 NOT NULL,
                "trade_fee_rate" INT8 NOT NULL,
                "tick_spacing" INT4 NOT NULL,
                "fund_fee_rate" INT8 NOT NULL,
                "padding_u32" INT8 NOT NULL,
                "fund_owner" BYTEA NOT NULL,
                "padding" NUMERIC(20)[] NOT NULL,
                -- Account metadata
                __pubkey BYTEA NOT NULL,
                __slot NUMERIC(20),
                PRIMARY KEY (__pubkey)
            )"#,
        )
        .execute(connection)
        .await?;
        Ok(())
    }

    async fn down(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(r#"DROP TABLE IF EXISTS amm_config_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}
