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

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct TickArrayStateRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub pool_id: Pubkey,
    pub start_tick_index: i32,
    pub ticks: sqlx::types::Json<Vec<TickState>>,
    pub initialized_tick_count: U8,
    pub recent_epoch: U64,
    pub padding: Vec<u8>,
}

impl TickArrayStateRow {
    pub fn from_parts(
        source: crate::accounts::tick_array_state::TickArrayState,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            pool_id: source.pool_id.into(),
            start_tick_index: source.start_tick_index,
            ticks: sqlx::types::Json(source.ticks.to_vec()),
            initialized_tick_count: source.initialized_tick_count.into(),
            recent_epoch: source.recent_epoch.into(),
            padding: source.padding.to_vec(),
        }
    }
}

impl TryFrom<TickArrayStateRow> for crate::accounts::tick_array_state::TickArrayState {
    type Error = carbon_core::error::Error;
    fn try_from(source: TickArrayStateRow) -> Result<Self, Self::Error> {
        Ok(Self {
            pool_id: *source.pool_id,
            start_tick_index: source.start_tick_index,
            ticks: source
                .ticks
                .0
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
            initialized_tick_count: source.initialized_tick_count.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.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 107 bytes"
                        .to_string(),
                )
            })?,
        })
    }
}

impl carbon_core::postgres::operations::Table
    for crate::accounts::tick_array_state::TickArrayState
{
    fn table() -> &'static str {
        "tick_array_state_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "pool_id",
            "start_tick_index",
            "ticks",
            "initialized_tick_count",
            "recent_epoch",
            "padding",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for TickArrayStateRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO tick_array_state_account (
                "pool_id",
                "start_tick_index",
                "ticks",
                "initialized_tick_count",
                "recent_epoch",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8
            )"#,
        )
        .bind(self.pool_id)
        .bind(self.start_tick_index)
        .bind(&self.ticks)
        .bind(self.initialized_tick_count)
        .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 TickArrayStateRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO tick_array_state_account (
                "pool_id",
                "start_tick_index",
                "ticks",
                "initialized_tick_count",
                "recent_epoch",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "pool_id" = EXCLUDED."pool_id",
                "start_tick_index" = EXCLUDED."start_tick_index",
                "ticks" = EXCLUDED."ticks",
                "initialized_tick_count" = EXCLUDED."initialized_tick_count",
                "recent_epoch" = EXCLUDED."recent_epoch",
                "padding" = EXCLUDED."padding",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(self.pool_id)
        .bind(self.start_tick_index)
        .bind(&self.ticks)
        .bind(self.initialized_tick_count)
        .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 TickArrayStateRow {
    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_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 TickArrayStateRow {
    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_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 TickArrayStateMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for TickArrayStateMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS tick_array_state_account (
                -- Account data
                "pool_id" BYTEA NOT NULL,
                "start_tick_index" INT4 NOT NULL,
                "ticks" JSONB NOT NULL,
                "initialized_tick_count" INT2 NOT NULL,
                "recent_epoch" NUMERIC(20) NOT NULL,
                "padding" BYTEA 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_state_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}
