//! This code was AUTOGENERATED using the Codama library.
use carbon_core::{
    instruction::InstructionMetadata,
    postgres::{
        metadata::InstructionRowMetadata,
        primitives::{U128, U64},
    },
};

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct OpenPositionWithToken22NftRow {
    #[sqlx(flatten)]
    pub instruction_metadata: InstructionRowMetadata,
    pub tick_lower_index: i32,
    pub tick_upper_index: i32,
    pub tick_array_lower_start_index: i32,
    pub tick_array_upper_start_index: i32,
    pub liquidity: U128,
    pub amount0_max: U64,
    pub amount1_max: U64,
    pub with_metadata: bool,
    pub base_flag: Option<bool>,
    #[sqlx(rename = "__accounts")]
    pub accounts: sqlx::types::Json<Vec<solana_instruction::AccountMeta>>,
}

impl OpenPositionWithToken22NftRow {
    pub fn from_parts(
        source: crate::instructions::open_position_with_token22_nft::OpenPositionWithToken22Nft,
        metadata: InstructionMetadata,
        accounts: Vec<solana_instruction::AccountMeta>,
    ) -> Self {
        Self {
            instruction_metadata: metadata.into(),
            tick_lower_index: source.tick_lower_index,
            tick_upper_index: source.tick_upper_index,
            tick_array_lower_start_index: source.tick_array_lower_start_index,
            tick_array_upper_start_index: source.tick_array_upper_start_index,
            liquidity: source.liquidity.into(),
            amount0_max: source.amount0_max.into(),
            amount1_max: source.amount1_max.into(),
            with_metadata: source.with_metadata,
            base_flag: source.base_flag,
            accounts: sqlx::types::Json(accounts),
        }
    }
}

impl TryFrom<OpenPositionWithToken22NftRow>
    for crate::instructions::open_position_with_token22_nft::OpenPositionWithToken22Nft
{
    type Error = carbon_core::error::Error;
    fn try_from(source: OpenPositionWithToken22NftRow) -> Result<Self, Self::Error> {
        Ok(Self {
            tick_lower_index: source.tick_lower_index,
            tick_upper_index: source.tick_upper_index,
            tick_array_lower_start_index: source.tick_array_lower_start_index,
            tick_array_upper_start_index: source.tick_array_upper_start_index,
            liquidity: *source.liquidity,
            amount0_max: *source.amount0_max,
            amount1_max: *source.amount1_max,
            with_metadata: source.with_metadata,
            base_flag: source.base_flag,
        })
    }
}

impl carbon_core::postgres::operations::Table
    for crate::instructions::open_position_with_token22_nft::OpenPositionWithToken22Nft
{
    fn table() -> &'static str {
        "open_position_with_token22_nft_instruction"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__signature",
            "__instruction_index",
            "__stack_height",
            "__slot",
            "tick_lower_index",
            "tick_upper_index",
            "tick_array_lower_start_index",
            "tick_array_upper_start_index",
            "liquidity",
            "amount0_max",
            "amount1_max",
            "with_metadata",
            "base_flag",
            "__accounts",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for OpenPositionWithToken22NftRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO open_position_with_token22_nft_instruction (
                "tick_lower_index",
                "tick_upper_index",
                "tick_array_lower_start_index",
                "tick_array_upper_start_index",
                "liquidity",
                "amount0_max",
                "amount1_max",
                "with_metadata",
                "base_flag",
                __signature, __instruction_index, __stack_height, __slot, __accounts
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
            )"#,
        )
        .bind(self.tick_lower_index)
        .bind(self.tick_upper_index)
        .bind(self.tick_array_lower_start_index)
        .bind(self.tick_array_upper_start_index)
        .bind(&self.liquidity)
        .bind(&self.amount0_max)
        .bind(&self.amount1_max)
        .bind(self.with_metadata)
        .bind(self.base_flag)
        .bind(&self.instruction_metadata.signature)
        .bind(self.instruction_metadata.instruction_index)
        .bind(self.instruction_metadata.stack_height)
        .bind(&self.instruction_metadata.slot)
        .bind(&self.accounts)
        .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 OpenPositionWithToken22NftRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO open_position_with_token22_nft_instruction (
                "tick_lower_index",
                "tick_upper_index",
                "tick_array_lower_start_index",
                "tick_array_upper_start_index",
                "liquidity",
                "amount0_max",
                "amount1_max",
                "with_metadata",
                "base_flag",
                __signature, __instruction_index, __stack_height, __slot, __accounts
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
            ) ON CONFLICT (
                __signature, __instruction_index, __stack_height
            ) DO UPDATE SET
                "tick_lower_index" = EXCLUDED."tick_lower_index",
                "tick_upper_index" = EXCLUDED."tick_upper_index",
                "tick_array_lower_start_index" = EXCLUDED."tick_array_lower_start_index",
                "tick_array_upper_start_index" = EXCLUDED."tick_array_upper_start_index",
                "liquidity" = EXCLUDED."liquidity",
                "amount0_max" = EXCLUDED."amount0_max",
                "amount1_max" = EXCLUDED."amount1_max",
                "with_metadata" = EXCLUDED."with_metadata",
                "base_flag" = EXCLUDED."base_flag",
                __instruction_index = EXCLUDED.__instruction_index,
                __stack_height = EXCLUDED.__stack_height,
                __slot = EXCLUDED.__slot,
                __accounts = EXCLUDED.__accounts
            "#,
        )
        .bind(self.tick_lower_index)
        .bind(self.tick_upper_index)
        .bind(self.tick_array_lower_start_index)
        .bind(self.tick_array_upper_start_index)
        .bind(&self.liquidity)
        .bind(&self.amount0_max)
        .bind(&self.amount1_max)
        .bind(self.with_metadata)
        .bind(self.base_flag)
        .bind(&self.instruction_metadata.signature)
        .bind(self.instruction_metadata.instruction_index)
        .bind(self.instruction_metadata.stack_height)
        .bind(&self.instruction_metadata.slot)
        .bind(&self.accounts)
        .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 OpenPositionWithToken22NftRow {
    type Key = (
        String,
        carbon_core::postgres::primitives::U32,
        carbon_core::postgres::primitives::U32,
    );

    async fn delete(key: Self::Key, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"DELETE FROM open_position_with_token22_nft_instruction WHERE
                __signature = $1 AND __instruction_index = $2 AND __stack_height = $3
            "#,
        )
        .bind(key.0)
        .bind(key.1)
        .bind(key.2)
        .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 OpenPositionWithToken22NftRow {
    type Key = (
        String,
        carbon_core::postgres::primitives::U32,
        carbon_core::postgres::primitives::U32,
    );

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

pub struct OpenPositionWithToken22NftMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for OpenPositionWithToken22NftMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS open_position_with_token22_nft_instruction (
                -- Instruction data
                "tick_lower_index" INT4 NOT NULL,
                "tick_upper_index" INT4 NOT NULL,
                "tick_array_lower_start_index" INT4 NOT NULL,
                "tick_array_upper_start_index" INT4 NOT NULL,
                "liquidity" NUMERIC(39) NOT NULL,
                "amount0_max" NUMERIC(20) NOT NULL,
                "amount1_max" NUMERIC(20) NOT NULL,
                "with_metadata" BOOLEAN NOT NULL,
                "base_flag" BOOLEAN,
                -- Instruction metadata
                __signature TEXT NOT NULL,
                __instruction_index BIGINT NOT NULL,
                __stack_height BIGINT NOT NULL,
                __slot NUMERIC(20),
                __accounts JSONB NOT NULL,
                PRIMARY KEY (__signature, __instruction_index, __stack_height)
            )"#,
        )
        .execute(connection)
        .await?;
        Ok(())
    }

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