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

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct PersonalPositionStateRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub bump: Vec<u8>,
    pub nft_mint: Pubkey,
    pub pool_id: Pubkey,
    pub tick_lower_index: i32,
    pub tick_upper_index: i32,
    pub liquidity: U128,
    pub fee_growth_inside0_last_x64: U128,
    pub fee_growth_inside1_last_x64: U128,
    pub token_fees_owed0: U64,
    pub token_fees_owed1: U64,
    pub reward_infos: sqlx::types::Json<Vec<PositionRewardInfo>>,
    pub recent_epoch: U64,
    pub padding: Vec<U64>,
}

impl PersonalPositionStateRow {
    pub fn from_parts(
        source: crate::accounts::personal_position_state::PersonalPositionState,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            bump: source.bump.to_vec(),
            nft_mint: source.nft_mint.into(),
            pool_id: source.pool_id.into(),
            tick_lower_index: source.tick_lower_index,
            tick_upper_index: source.tick_upper_index,
            liquidity: source.liquidity.into(),
            fee_growth_inside0_last_x64: source.fee_growth_inside0_last_x64.into(),
            fee_growth_inside1_last_x64: source.fee_growth_inside1_last_x64.into(),
            token_fees_owed0: source.token_fees_owed0.into(),
            token_fees_owed1: source.token_fees_owed1.into(),
            reward_infos: sqlx::types::Json(source.reward_infos.to_vec()),
            recent_epoch: source.recent_epoch.into(),
            padding: source
                .padding
                .into_iter()
                .map(|element| element.into())
                .collect(),
        }
    }
}

impl TryFrom<PersonalPositionStateRow>
    for crate::accounts::personal_position_state::PersonalPositionState
{
    type Error = carbon_core::error::Error;
    fn try_from(source: PersonalPositionStateRow) -> 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(),
                )
            })?,
            nft_mint: *source.nft_mint,
            pool_id: *source.pool_id,
            tick_lower_index: source.tick_lower_index,
            tick_upper_index: source.tick_upper_index,
            liquidity: *source.liquidity,
            fee_growth_inside0_last_x64: *source.fee_growth_inside0_last_x64,
            fee_growth_inside1_last_x64: *source.fee_growth_inside1_last_x64,
            token_fees_owed0: *source.token_fees_owed0,
            token_fees_owed1: *source.token_fees_owed1,
            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(),
                    )
                })?,
            recent_epoch: *source.recent_epoch,
            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::personal_position_state::PersonalPositionState
{
    fn table() -> &'static str {
        "personal_position_state_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "bump",
            "nft_mint",
            "pool_id",
            "tick_lower_index",
            "tick_upper_index",
            "liquidity",
            "fee_growth_inside0_last_x64",
            "fee_growth_inside1_last_x64",
            "token_fees_owed0",
            "token_fees_owed1",
            "reward_infos",
            "recent_epoch",
            "padding",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for PersonalPositionStateRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO personal_position_state_account (
                "bump",
                "nft_mint",
                "pool_id",
                "tick_lower_index",
                "tick_upper_index",
                "liquidity",
                "fee_growth_inside0_last_x64",
                "fee_growth_inside1_last_x64",
                "token_fees_owed0",
                "token_fees_owed1",
                "reward_infos",
                "recent_epoch",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15
            )"#,
        )
        .bind(&self.bump)
        .bind(self.nft_mint)
        .bind(self.pool_id)
        .bind(self.tick_lower_index)
        .bind(self.tick_upper_index)
        .bind(&self.liquidity)
        .bind(&self.fee_growth_inside0_last_x64)
        .bind(&self.fee_growth_inside1_last_x64)
        .bind(&self.token_fees_owed0)
        .bind(&self.token_fees_owed1)
        .bind(&self.reward_infos)
        .bind(&self.recent_epoch)
        .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 PersonalPositionStateRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO personal_position_state_account (
                "bump",
                "nft_mint",
                "pool_id",
                "tick_lower_index",
                "tick_upper_index",
                "liquidity",
                "fee_growth_inside0_last_x64",
                "fee_growth_inside1_last_x64",
                "token_fees_owed0",
                "token_fees_owed1",
                "reward_infos",
                "recent_epoch",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "bump" = EXCLUDED."bump",
                "nft_mint" = EXCLUDED."nft_mint",
                "pool_id" = EXCLUDED."pool_id",
                "tick_lower_index" = EXCLUDED."tick_lower_index",
                "tick_upper_index" = EXCLUDED."tick_upper_index",
                "liquidity" = EXCLUDED."liquidity",
                "fee_growth_inside0_last_x64" = EXCLUDED."fee_growth_inside0_last_x64",
                "fee_growth_inside1_last_x64" = EXCLUDED."fee_growth_inside1_last_x64",
                "token_fees_owed0" = EXCLUDED."token_fees_owed0",
                "token_fees_owed1" = EXCLUDED."token_fees_owed1",
                "reward_infos" = EXCLUDED."reward_infos",
                "recent_epoch" = EXCLUDED."recent_epoch",
                "padding" = EXCLUDED."padding",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(&self.bump)
        .bind(self.nft_mint)
        .bind(self.pool_id)
        .bind(self.tick_lower_index)
        .bind(self.tick_upper_index)
        .bind(&self.liquidity)
        .bind(&self.fee_growth_inside0_last_x64)
        .bind(&self.fee_growth_inside1_last_x64)
        .bind(&self.token_fees_owed0)
        .bind(&self.token_fees_owed1)
        .bind(&self.reward_infos)
        .bind(&self.recent_epoch)
        .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 PersonalPositionStateRow {
    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 personal_position_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 PersonalPositionStateRow {
    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 personal_position_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 PersonalPositionStateMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for PersonalPositionStateMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS personal_position_state_account (
                -- Account data
                "bump" BYTEA NOT NULL,
                "nft_mint" BYTEA NOT NULL,
                "pool_id" BYTEA NOT NULL,
                "tick_lower_index" INT4 NOT NULL,
                "tick_upper_index" INT4 NOT NULL,
                "liquidity" NUMERIC(39) NOT NULL,
                "fee_growth_inside0_last_x64" NUMERIC(39) NOT NULL,
                "fee_growth_inside1_last_x64" NUMERIC(39) NOT NULL,
                "token_fees_owed0" NUMERIC(20) NOT NULL,
                "token_fees_owed1" NUMERIC(20) NOT NULL,
                "reward_infos" JSONB NOT NULL,
                "recent_epoch" NUMERIC(20) 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 personal_position_state_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}
