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

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct TickArrayBitmapExtensionRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub pool_id: Pubkey,
    pub positive_tick_array_bitmap: sqlx::types::Json<Vec<Vec<U64>>>,
    pub negative_tick_array_bitmap: sqlx::types::Json<Vec<Vec<U64>>>,
}

impl TickArrayBitmapExtensionRow {
    pub fn from_parts(
        source: crate::accounts::tick_array_bitmap_extension::TickArrayBitmapExtension,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            pool_id: source.pool_id.into(),
            positive_tick_array_bitmap: sqlx::types::Json(
                source
                    .positive_tick_array_bitmap
                    .into_iter()
                    .map(|element| element.into_iter().map(|element| element.into()).collect())
                    .collect(),
            ),
            negative_tick_array_bitmap: sqlx::types::Json(
                source
                    .negative_tick_array_bitmap
                    .into_iter()
                    .map(|element| element.into_iter().map(|element| element.into()).collect())
                    .collect(),
            ),
        }
    }
}

impl TryFrom<TickArrayBitmapExtensionRow>
    for crate::accounts::tick_array_bitmap_extension::TickArrayBitmapExtension
{
    type Error = carbon_core::error::Error;
    fn try_from(source: TickArrayBitmapExtensionRow) -> Result<Self, Self::Error> {
        Ok(Self {
            pool_id: *source.pool_id,
            positive_tick_array_bitmap: source
                .positive_tick_array_bitmap
                .0
                .into_iter()
                .map(|element| {
                    element
                        .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(),
                            )
                        })
                })
                .collect::<Result<Vec<_>, carbon_core::error::Error>>()?
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
            negative_tick_array_bitmap: source
                .negative_tick_array_bitmap
                .0
                .into_iter()
                .map(|element| {
                    element
                        .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(),
                            )
                        })
                })
                .collect::<Result<Vec<_>, carbon_core::error::Error>>()?
                .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 crate::accounts::tick_array_bitmap_extension::TickArrayBitmapExtension
{
    fn table() -> &'static str {
        "tick_array_bitmap_extension_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "pool_id",
            "positive_tick_array_bitmap",
            "negative_tick_array_bitmap",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for TickArrayBitmapExtensionRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO tick_array_bitmap_extension_account (
                "pool_id",
                "positive_tick_array_bitmap",
                "negative_tick_array_bitmap",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5
            )"#,
        )
        .bind(self.pool_id)
        .bind(&self.positive_tick_array_bitmap)
        .bind(&self.negative_tick_array_bitmap)
        .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 TickArrayBitmapExtensionRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO tick_array_bitmap_extension_account (
                "pool_id",
                "positive_tick_array_bitmap",
                "negative_tick_array_bitmap",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "pool_id" = EXCLUDED."pool_id",
                "positive_tick_array_bitmap" = EXCLUDED."positive_tick_array_bitmap",
                "negative_tick_array_bitmap" = EXCLUDED."negative_tick_array_bitmap",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(self.pool_id)
        .bind(&self.positive_tick_array_bitmap)
        .bind(&self.negative_tick_array_bitmap)
        .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 TickArrayBitmapExtensionRow {
    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 tick_array_bitmap_extension_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 TickArrayBitmapExtensionRow {
    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 tick_array_bitmap_extension_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 TickArrayBitmapExtensionMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for TickArrayBitmapExtensionMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS tick_array_bitmap_extension_account (
                -- Account data
                "pool_id" BYTEA NOT NULL,
                "positive_tick_array_bitmap" JSONB NOT NULL,
                "negative_tick_array_bitmap" JSONB 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 tick_array_bitmap_extension_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}
