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

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct PoolStateRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub bump: Vec<u8>,
    pub amm_config: Pubkey,
    pub owner: Pubkey,
    pub token_mint0: Pubkey,
    pub token_mint1: Pubkey,
    pub token_vault0: Pubkey,
    pub token_vault1: Pubkey,
    pub observation_key: Pubkey,
    pub mint_decimals0: U8,
    pub mint_decimals1: U8,
    pub tick_spacing: U16,
    pub liquidity: U128,
    pub sqrt_price_x64: U128,
    pub tick_current: i32,
    pub padding3: U16,
    pub padding4: U16,
    pub fee_growth_global0_x64: U128,
    pub fee_growth_global1_x64: U128,
    pub protocol_fees_token0: U64,
    pub protocol_fees_token1: U64,
    pub swap_in_amount_token0: U128,
    pub swap_out_amount_token1: U128,
    pub swap_in_amount_token1: U128,
    pub swap_out_amount_token0: U128,
    pub status: U8,
    pub padding: Vec<u8>,
    pub reward_infos: sqlx::types::Json<Vec<RewardInfo>>,
    pub tick_array_bitmap: Vec<U64>,
    pub total_fees_token0: U64,
    pub total_fees_claimed_token0: U64,
    pub total_fees_token1: U64,
    pub total_fees_claimed_token1: U64,
    pub fund_fees_token0: U64,
    pub fund_fees_token1: U64,
    pub open_time: U64,
    pub recent_epoch: U64,
    pub padding1: Vec<U64>,
    pub padding2: Vec<U64>,
}

impl PoolStateRow {
    pub fn from_parts(
        source: crate::accounts::pool_state::PoolState,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            bump: source.bump.to_vec(),
            amm_config: source.amm_config.into(),
            owner: source.owner.into(),
            token_mint0: source.token_mint0.into(),
            token_mint1: source.token_mint1.into(),
            token_vault0: source.token_vault0.into(),
            token_vault1: source.token_vault1.into(),
            observation_key: source.observation_key.into(),
            mint_decimals0: source.mint_decimals0.into(),
            mint_decimals1: source.mint_decimals1.into(),
            tick_spacing: source.tick_spacing.into(),
            liquidity: source.liquidity.into(),
            sqrt_price_x64: source.sqrt_price_x64.into(),
            tick_current: source.tick_current,
            padding3: source.padding3.into(),
            padding4: source.padding4.into(),
            fee_growth_global0_x64: source.fee_growth_global0_x64.into(),
            fee_growth_global1_x64: source.fee_growth_global1_x64.into(),
            protocol_fees_token0: source.protocol_fees_token0.into(),
            protocol_fees_token1: source.protocol_fees_token1.into(),
            swap_in_amount_token0: source.swap_in_amount_token0.into(),
            swap_out_amount_token1: source.swap_out_amount_token1.into(),
            swap_in_amount_token1: source.swap_in_amount_token1.into(),
            swap_out_amount_token0: source.swap_out_amount_token0.into(),
            status: source.status.into(),
            padding: source.padding.to_vec(),
            reward_infos: sqlx::types::Json(source.reward_infos.to_vec()),
            tick_array_bitmap: source
                .tick_array_bitmap
                .into_iter()
                .map(|element| element.into())
                .collect(),
            total_fees_token0: source.total_fees_token0.into(),
            total_fees_claimed_token0: source.total_fees_claimed_token0.into(),
            total_fees_token1: source.total_fees_token1.into(),
            total_fees_claimed_token1: source.total_fees_claimed_token1.into(),
            fund_fees_token0: source.fund_fees_token0.into(),
            fund_fees_token1: source.fund_fees_token1.into(),
            open_time: source.open_time.into(),
            recent_epoch: source.recent_epoch.into(),
            padding1: source
                .padding1
                .into_iter()
                .map(|element| element.into())
                .collect(),
            padding2: source
                .padding2
                .into_iter()
                .map(|element| element.into())
                .collect(),
        }
    }
}

impl TryFrom<PoolStateRow> for crate::accounts::pool_state::PoolState {
    type Error = carbon_core::error::Error;
    fn try_from(source: PoolStateRow) -> Result<Self, Self::Error> {
        Ok(Self {
            bump: source.bump.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 1 bytes"
                        .to_string(),
                )
            })?,
            amm_config: *source.amm_config,
            owner: *source.owner,
            token_mint0: *source.token_mint0,
            token_mint1: *source.token_mint1,
            token_vault0: *source.token_vault0,
            token_vault1: *source.token_vault1,
            observation_key: *source.observation_key,
            mint_decimals0: source.mint_decimals0.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            mint_decimals1: source.mint_decimals1.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(),
                )
            })?,
            liquidity: *source.liquidity,
            sqrt_price_x64: *source.sqrt_price_x64,
            tick_current: source.tick_current,
            padding3: source.padding3.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            padding4: source.padding4.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            fee_growth_global0_x64: *source.fee_growth_global0_x64,
            fee_growth_global1_x64: *source.fee_growth_global1_x64,
            protocol_fees_token0: *source.protocol_fees_token0,
            protocol_fees_token1: *source.protocol_fees_token1,
            swap_in_amount_token0: *source.swap_in_amount_token0,
            swap_out_amount_token1: *source.swap_out_amount_token1,
            swap_in_amount_token1: *source.swap_in_amount_token1,
            swap_out_amount_token0: *source.swap_out_amount_token0,
            status: source.status.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            padding: source.padding.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 7 bytes"
                        .to_string(),
                )
            })?,
            reward_infos: source
                .reward_infos
                .0
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
            tick_array_bitmap: source
                .tick_array_bitmap
                .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(),
                    )
                })?,
            total_fees_token0: *source.total_fees_token0,
            total_fees_claimed_token0: *source.total_fees_claimed_token0,
            total_fees_token1: *source.total_fees_token1,
            total_fees_claimed_token1: *source.total_fees_claimed_token1,
            fund_fees_token0: *source.fund_fees_token0,
            fund_fees_token1: *source.fund_fees_token1,
            open_time: *source.open_time,
            recent_epoch: *source.recent_epoch,
            padding1: source
                .padding1
                .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(),
                    )
                })?,
            padding2: source
                .padding2
                .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::pool_state::PoolState {
    fn table() -> &'static str {
        "pool_state_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "bump",
            "amm_config",
            "owner",
            "token_mint0",
            "token_mint1",
            "token_vault0",
            "token_vault1",
            "observation_key",
            "mint_decimals0",
            "mint_decimals1",
            "tick_spacing",
            "liquidity",
            "sqrt_price_x64",
            "tick_current",
            "padding3",
            "padding4",
            "fee_growth_global0_x64",
            "fee_growth_global1_x64",
            "protocol_fees_token0",
            "protocol_fees_token1",
            "swap_in_amount_token0",
            "swap_out_amount_token1",
            "swap_in_amount_token1",
            "swap_out_amount_token0",
            "status",
            "padding",
            "reward_infos",
            "tick_array_bitmap",
            "total_fees_token0",
            "total_fees_claimed_token0",
            "total_fees_token1",
            "total_fees_claimed_token1",
            "fund_fees_token0",
            "fund_fees_token1",
            "open_time",
            "recent_epoch",
            "padding1",
            "padding2",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for PoolStateRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"
            INSERT INTO pool_state_account (
                "bump",
                "amm_config",
                "owner",
                "token_mint0",
                "token_mint1",
                "token_vault0",
                "token_vault1",
                "observation_key",
                "mint_decimals0",
                "mint_decimals1",
                "tick_spacing",
                "liquidity",
                "sqrt_price_x64",
                "tick_current",
                "padding3",
                "padding4",
                "fee_growth_global0_x64",
                "fee_growth_global1_x64",
                "protocol_fees_token0",
                "protocol_fees_token1",
                "swap_in_amount_token0",
                "swap_out_amount_token1",
                "swap_in_amount_token1",
                "swap_out_amount_token0",
                "status",
                "padding",
                "reward_infos",
                "tick_array_bitmap",
                "total_fees_token0",
                "total_fees_claimed_token0",
                "total_fees_token1",
                "total_fees_claimed_token1",
                "fund_fees_token0",
                "fund_fees_token1",
                "open_time",
                "recent_epoch",
                "padding1",
                "padding2",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40
            )"#)
        .bind(&self.bump)
        .bind(self.amm_config)
        .bind(self.owner)
        .bind(self.token_mint0)
        .bind(self.token_mint1)
        .bind(self.token_vault0)
        .bind(self.token_vault1)
        .bind(self.observation_key)
        .bind(self.mint_decimals0)
        .bind(self.mint_decimals1)
        .bind(self.tick_spacing)
        .bind(&self.liquidity)
        .bind(&self.sqrt_price_x64)
        .bind(self.tick_current)
        .bind(self.padding3)
        .bind(self.padding4)
        .bind(&self.fee_growth_global0_x64)
        .bind(&self.fee_growth_global1_x64)
        .bind(&self.protocol_fees_token0)
        .bind(&self.protocol_fees_token1)
        .bind(&self.swap_in_amount_token0)
        .bind(&self.swap_out_amount_token1)
        .bind(&self.swap_in_amount_token1)
        .bind(&self.swap_out_amount_token0)
        .bind(self.status)
        .bind(&self.padding)
        .bind(&self.reward_infos)
        .bind(&self.tick_array_bitmap)
        .bind(&self.total_fees_token0)
        .bind(&self.total_fees_claimed_token0)
        .bind(&self.total_fees_token1)
        .bind(&self.total_fees_claimed_token1)
        .bind(&self.fund_fees_token0)
        .bind(&self.fund_fees_token1)
        .bind(&self.open_time)
        .bind(&self.recent_epoch)
        .bind(&self.padding1)
        .bind(&self.padding2)
        .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 PoolStateRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"INSERT INTO pool_state_account (
                "bump",
                "amm_config",
                "owner",
                "token_mint0",
                "token_mint1",
                "token_vault0",
                "token_vault1",
                "observation_key",
                "mint_decimals0",
                "mint_decimals1",
                "tick_spacing",
                "liquidity",
                "sqrt_price_x64",
                "tick_current",
                "padding3",
                "padding4",
                "fee_growth_global0_x64",
                "fee_growth_global1_x64",
                "protocol_fees_token0",
                "protocol_fees_token1",
                "swap_in_amount_token0",
                "swap_out_amount_token1",
                "swap_in_amount_token1",
                "swap_out_amount_token0",
                "status",
                "padding",
                "reward_infos",
                "tick_array_bitmap",
                "total_fees_token0",
                "total_fees_claimed_token0",
                "total_fees_token1",
                "total_fees_claimed_token1",
                "fund_fees_token0",
                "fund_fees_token1",
                "open_time",
                "recent_epoch",
                "padding1",
                "padding2",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "bump" = EXCLUDED."bump",
                "amm_config" = EXCLUDED."amm_config",
                "owner" = EXCLUDED."owner",
                "token_mint0" = EXCLUDED."token_mint0",
                "token_mint1" = EXCLUDED."token_mint1",
                "token_vault0" = EXCLUDED."token_vault0",
                "token_vault1" = EXCLUDED."token_vault1",
                "observation_key" = EXCLUDED."observation_key",
                "mint_decimals0" = EXCLUDED."mint_decimals0",
                "mint_decimals1" = EXCLUDED."mint_decimals1",
                "tick_spacing" = EXCLUDED."tick_spacing",
                "liquidity" = EXCLUDED."liquidity",
                "sqrt_price_x64" = EXCLUDED."sqrt_price_x64",
                "tick_current" = EXCLUDED."tick_current",
                "padding3" = EXCLUDED."padding3",
                "padding4" = EXCLUDED."padding4",
                "fee_growth_global0_x64" = EXCLUDED."fee_growth_global0_x64",
                "fee_growth_global1_x64" = EXCLUDED."fee_growth_global1_x64",
                "protocol_fees_token0" = EXCLUDED."protocol_fees_token0",
                "protocol_fees_token1" = EXCLUDED."protocol_fees_token1",
                "swap_in_amount_token0" = EXCLUDED."swap_in_amount_token0",
                "swap_out_amount_token1" = EXCLUDED."swap_out_amount_token1",
                "swap_in_amount_token1" = EXCLUDED."swap_in_amount_token1",
                "swap_out_amount_token0" = EXCLUDED."swap_out_amount_token0",
                "status" = EXCLUDED."status",
                "padding" = EXCLUDED."padding",
                "reward_infos" = EXCLUDED."reward_infos",
                "tick_array_bitmap" = EXCLUDED."tick_array_bitmap",
                "total_fees_token0" = EXCLUDED."total_fees_token0",
                "total_fees_claimed_token0" = EXCLUDED."total_fees_claimed_token0",
                "total_fees_token1" = EXCLUDED."total_fees_token1",
                "total_fees_claimed_token1" = EXCLUDED."total_fees_claimed_token1",
                "fund_fees_token0" = EXCLUDED."fund_fees_token0",
                "fund_fees_token1" = EXCLUDED."fund_fees_token1",
                "open_time" = EXCLUDED."open_time",
                "recent_epoch" = EXCLUDED."recent_epoch",
                "padding1" = EXCLUDED."padding1",
                "padding2" = EXCLUDED."padding2",
                __slot = EXCLUDED.__slot
            "#)
        .bind(&self.bump)
        .bind(self.amm_config)
        .bind(self.owner)
        .bind(self.token_mint0)
        .bind(self.token_mint1)
        .bind(self.token_vault0)
        .bind(self.token_vault1)
        .bind(self.observation_key)
        .bind(self.mint_decimals0)
        .bind(self.mint_decimals1)
        .bind(self.tick_spacing)
        .bind(&self.liquidity)
        .bind(&self.sqrt_price_x64)
        .bind(self.tick_current)
        .bind(self.padding3)
        .bind(self.padding4)
        .bind(&self.fee_growth_global0_x64)
        .bind(&self.fee_growth_global1_x64)
        .bind(&self.protocol_fees_token0)
        .bind(&self.protocol_fees_token1)
        .bind(&self.swap_in_amount_token0)
        .bind(&self.swap_out_amount_token1)
        .bind(&self.swap_in_amount_token1)
        .bind(&self.swap_out_amount_token0)
        .bind(self.status)
        .bind(&self.padding)
        .bind(&self.reward_infos)
        .bind(&self.tick_array_bitmap)
        .bind(&self.total_fees_token0)
        .bind(&self.total_fees_claimed_token0)
        .bind(&self.total_fees_token1)
        .bind(&self.total_fees_claimed_token1)
        .bind(&self.fund_fees_token0)
        .bind(&self.fund_fees_token1)
        .bind(&self.open_time)
        .bind(&self.recent_epoch)
        .bind(&self.padding1)
        .bind(&self.padding2)
        .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 PoolStateRow {
    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 pool_state_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 PoolStateRow {
    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 pool_state_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 PoolStateMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for PoolStateMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS pool_state_account (
                -- Account data
                "bump" BYTEA NOT NULL,
                "amm_config" BYTEA NOT NULL,
                "owner" BYTEA NOT NULL,
                "token_mint0" BYTEA NOT NULL,
                "token_mint1" BYTEA NOT NULL,
                "token_vault0" BYTEA NOT NULL,
                "token_vault1" BYTEA NOT NULL,
                "observation_key" BYTEA NOT NULL,
                "mint_decimals0" INT2 NOT NULL,
                "mint_decimals1" INT2 NOT NULL,
                "tick_spacing" INT4 NOT NULL,
                "liquidity" NUMERIC(39) NOT NULL,
                "sqrt_price_x64" NUMERIC(39) NOT NULL,
                "tick_current" INT4 NOT NULL,
                "padding3" INT4 NOT NULL,
                "padding4" INT4 NOT NULL,
                "fee_growth_global0_x64" NUMERIC(39) NOT NULL,
                "fee_growth_global1_x64" NUMERIC(39) NOT NULL,
                "protocol_fees_token0" NUMERIC(20) NOT NULL,
                "protocol_fees_token1" NUMERIC(20) NOT NULL,
                "swap_in_amount_token0" NUMERIC(39) NOT NULL,
                "swap_out_amount_token1" NUMERIC(39) NOT NULL,
                "swap_in_amount_token1" NUMERIC(39) NOT NULL,
                "swap_out_amount_token0" NUMERIC(39) NOT NULL,
                "status" INT2 NOT NULL,
                "padding" BYTEA NOT NULL,
                "reward_infos" JSONB NOT NULL,
                "tick_array_bitmap" NUMERIC(20)[] NOT NULL,
                "total_fees_token0" NUMERIC(20) NOT NULL,
                "total_fees_claimed_token0" NUMERIC(20) NOT NULL,
                "total_fees_token1" NUMERIC(20) NOT NULL,
                "total_fees_claimed_token1" NUMERIC(20) NOT NULL,
                "fund_fees_token0" NUMERIC(20) NOT NULL,
                "fund_fees_token1" NUMERIC(20) NOT NULL,
                "open_time" NUMERIC(20) NOT NULL,
                "recent_epoch" NUMERIC(20) NOT NULL,
                "padding1" NUMERIC(20)[] NOT NULL,
                "padding2" 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 pool_state_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}
