//! This code was AUTOGENERATED using the Codama library.
//! Please DO NOT EDIT THIS FILE, instead use visitors
//! to add features, then rerun Codama to update it.
//!
//! <https://github.com/codama-idl/codama>
//!

use crate::instructions::CreatePool;
use crate::types::FixedPoint;
use crate::types::Token;
use carbon_core::instruction::InstructionMetadata;
use carbon_core::postgres::metadata::InstructionRowMetadata;
use carbon_core::postgres::primitives::U8;

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct CreatePoolRow {
    #[sqlx(flatten)]
    pub metadata: InstructionRowMetadata,
    pub lp_fee: sqlx::types::Json<FixedPoint>,
    pub buyback_fee: sqlx::types::Json<FixedPoint>,
    pub project_fee: sqlx::types::Json<FixedPoint>,
    pub mercanti_fee: sqlx::types::Json<FixedPoint>,
    pub initial_token_x: sqlx::types::Json<Token>,
    pub initial_token_y: sqlx::types::Json<Token>,
    pub bump: U8,
}

impl CreatePoolRow {
    pub fn from_parts(source: CreatePool, metadata: InstructionMetadata) -> Self {
        Self {
            metadata: metadata.into(),
            lp_fee: sqlx::types::Json(source.lp_fee),
            buyback_fee: sqlx::types::Json(source.buyback_fee),
            project_fee: sqlx::types::Json(source.project_fee),
            mercanti_fee: sqlx::types::Json(source.mercanti_fee),
            initial_token_x: sqlx::types::Json(source.initial_token_x),
            initial_token_y: sqlx::types::Json(source.initial_token_y),
            bump: source.bump.into(),
        }
    }
}

impl TryFrom<CreatePoolRow> for CreatePool {
    type Error = carbon_core::error::Error;
    fn try_from(source: CreatePoolRow) -> Result<Self, Self::Error> {
        Ok(Self {
            lp_fee: source.lp_fee.0,
            buyback_fee: source.buyback_fee.0,
            project_fee: source.project_fee.0,
            mercanti_fee: source.mercanti_fee.0,
            initial_token_x: source.initial_token_x.0,
            initial_token_y: source.initial_token_y.0,
            bump: source.bump.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
        })
    }
}

impl carbon_core::postgres::operations::Table for CreatePool {
    fn table() -> &'static str {
        "create_pool_instruction"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__signature",
            "__instruction_index",
            "__stack_height",
            "__slot",
            "lp_fee",
            "buyback_fee",
            "project_fee",
            "mercanti_fee",
            "initial_token_x",
            "initial_token_y",
            "bump",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for CreatePoolRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"
            INSERT INTO create_pool_instruction (
                            "lp_fee",
                            "buyback_fee",
                            "project_fee",
                            "mercanti_fee",
                            "initial_token_x",
                            "initial_token_y",
                            "bump",
                                        __signature, __instruction_index, __stack_height, __slot
                        ) VALUES (
                                                                            $1,                            $2,                            $3,                            $4,                            $5,                            $6,                            $7,                            $8,                            $9,                            $10,                            $11                    )"#)
                .bind(self.lp_fee.clone())
                .bind(self.buyback_fee.clone())
                .bind(self.project_fee.clone())
                .bind(self.mercanti_fee.clone())
                .bind(self.initial_token_x.clone())
                .bind(self.initial_token_y.clone())
                .bind(self.bump)
                        .bind(self.metadata.signature.clone())
        .bind(self.metadata.instruction_index)
        .bind(self.metadata.stack_height)
        .bind(self.metadata.slot.clone())
                .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 CreatePoolRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"INSERT INTO create_pool_instruction (
                        "lp_fee",
                        "buyback_fee",
                        "project_fee",
                        "mercanti_fee",
                        "initial_token_x",
                        "initial_token_y",
                        "bump",
                                    __signature, __instruction_index, __stack_height, __slot
                    ) VALUES (
                                                                        $1,                        $2,                        $3,                        $4,                        $5,                        $6,                        $7,                        $8,                        $9,                        $10,                        $11                    ) ON CONFLICT (
                        __signature, __instruction_index
                    ) DO UPDATE SET
                        "lp_fee" = EXCLUDED."lp_fee",
                        "buyback_fee" = EXCLUDED."buyback_fee",
                        "project_fee" = EXCLUDED."project_fee",
                        "mercanti_fee" = EXCLUDED."mercanti_fee",
                        "initial_token_x" = EXCLUDED."initial_token_x",
                        "initial_token_y" = EXCLUDED."initial_token_y",
                        "bump" = EXCLUDED."bump",
                                    __instruction_index = EXCLUDED.__instruction_index,
            __stack_height = EXCLUDED.__stack_height,
            __slot = EXCLUDED.__slot
                    "#)
                .bind(self.lp_fee.clone())
                .bind(self.buyback_fee.clone())
                .bind(self.project_fee.clone())
                .bind(self.mercanti_fee.clone())
                .bind(self.initial_token_x.clone())
                .bind(self.initial_token_y.clone())
                .bind(self.bump)
                        .bind(self.metadata.signature.clone())
        .bind(self.metadata.instruction_index)
        .bind(self.metadata.stack_height)
        .bind(self.metadata.slot.clone())
                .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 CreatePoolRow {
    type Key = (String, carbon_core::postgres::primitives::U32);

    async fn delete(key: Self::Key, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"DELETE FROM create_pool_instruction WHERE
                        __signature = $1 AND __instruction_index = $2
                    "#,
        )
        .bind(key.0)
        .bind(key.1)
        .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 CreatePoolRow {
    type Key = (String, 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 create_pool_instruction WHERE
                        __signature = $1 AND __instruction_index = $2
                    "#,
        )
        .bind(key.0)
        .bind(key.1)
        .fetch_optional(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;

        Ok(row)
    }
}

pub struct CreatePoolMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for CreatePoolMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS create_pool_instruction (
                        -- Instruction data
                                    "lp_fee" JSONB NOT NULL,
                        "buyback_fee" JSONB NOT NULL,
                        "project_fee" JSONB NOT NULL,
                        "mercanti_fee" JSONB NOT NULL,
                        "initial_token_x" JSONB NOT NULL,
                        "initial_token_y" JSONB NOT NULL,
                        "bump" INT2 NOT NULL,
            
                        -- Instruction metadata
            __signature TEXT NOT NULL,
            __instruction_index BIGINT NOT NULL,
            __stack_height BIGINT NOT NULL,
            __slot NUMERIC(20),
            
                        PRIMARY KEY (__signature, __instruction_index)
                    )"#,
        )
        .execute(connection)
        .await?;
        Ok(())
    }

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