//! 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::accounts::Farm;
use crate::types::FarmType;
use crate::types::FixedPoint;
use crate::types::Token;
use carbon_core::account::AccountMetadata;
use carbon_core::postgres::metadata::AccountRowMetadata;
use carbon_core::postgres::primitives::Pubkey;
use carbon_core::postgres::primitives::U64;
use carbon_core::postgres::primitives::U8;

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct FarmRow {
    #[sqlx(flatten)]
    pub metadata: AccountRowMetadata,
    pub pool: Pubkey,
    pub tokens: Vec<Pubkey>,
    pub token_accounts: Vec<Pubkey>,
    pub supply: sqlx::types::Json<Vec<Token>>,
    pub supply_left: sqlx::types::Json<Vec<Token>>,
    pub accumulated_seconds_per_share: sqlx::types::Json<FixedPoint>,
    pub offset_seconds_per_share: sqlx::types::Json<FixedPoint>,
    pub start_time: U64,
    pub end_time: U64,
    pub last_update: U64,
    pub bump: U8,
    pub farm_type: sqlx::types::Json<FarmType>,
}

impl FarmRow {
    pub fn from_parts(source: Farm, metadata: AccountMetadata) -> Self {
        Self {
            metadata: metadata.into(),
            pool: source.pool.into(),
            tokens: source
                .tokens
                .into_iter()
                .map(|element| element.into())
                .collect(),
            token_accounts: source
                .token_accounts
                .into_iter()
                .map(|element| element.into())
                .collect(),
            supply: sqlx::types::Json(source.supply.into_iter().collect()),
            supply_left: sqlx::types::Json(source.supply_left.into_iter().collect()),
            accumulated_seconds_per_share: sqlx::types::Json(source.accumulated_seconds_per_share),
            offset_seconds_per_share: sqlx::types::Json(source.offset_seconds_per_share),
            start_time: source.start_time.into(),
            end_time: source.end_time.into(),
            last_update: source.last_update.into(),
            bump: source.bump.into(),
            farm_type: sqlx::types::Json(source.farm_type),
        }
    }
}

impl TryFrom<FarmRow> for Farm {
    type Error = carbon_core::error::Error;
    fn try_from(source: FarmRow) -> Result<Self, Self::Error> {
        Ok(Self {
            pool: *source.pool,
            tokens: source
                .tokens
                .into_iter()
                .map(|element| Ok(*element))
                .collect::<Result<Vec<_>, _>>()?
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert array element to primitive".to_string(),
                    )
                })?,
            token_accounts: source
                .token_accounts
                .into_iter()
                .map(|element| Ok(*element))
                .collect::<Result<Vec<_>, _>>()?
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert array element to primitive".to_string(),
                    )
                })?,
            supply: source
                .supply
                .0
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
            supply_left: source
                .supply_left
                .0
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
            accumulated_seconds_per_share: source.accumulated_seconds_per_share.0,
            offset_seconds_per_share: source.offset_seconds_per_share.0,
            start_time: *source.start_time,
            end_time: *source.end_time,
            last_update: *source.last_update,
            bump: source.bump.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            farm_type: source.farm_type.0,
        })
    }
}

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

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "pool",
            "tokens",
            "token_accounts",
            "supply",
            "supply_left",
            "accumulated_seconds_per_share",
            "offset_seconds_per_share",
            "start_time",
            "end_time",
            "last_update",
            "bump",
            "farm_type",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for FarmRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"
            INSERT INTO farm_account (
                            "pool",
                            "tokens",
                            "token_accounts",
                            "supply",
                            "supply_left",
                            "accumulated_seconds_per_share",
                            "offset_seconds_per_share",
                            "start_time",
                            "end_time",
                            "last_update",
                            "bump",
                            "farm_type",
                                        __pubkey, __slot
                        ) VALUES (
                                                                            $1,                            $2,                            $3,                            $4,                            $5,                            $6,                            $7,                            $8,                            $9,                            $10,                            $11,                            $12,                            $13,                            $14                    )"#)
                .bind(self.pool)
                .bind(self.tokens.clone())
                .bind(self.token_accounts.clone())
                .bind(self.supply.clone())
                .bind(self.supply_left.clone())
                .bind(self.accumulated_seconds_per_share.clone())
                .bind(self.offset_seconds_per_share.clone())
                .bind(self.start_time.clone())
                .bind(self.end_time.clone())
                .bind(self.last_update.clone())
                .bind(self.bump)
                .bind(self.farm_type.clone())
                        .bind(self.metadata.pubkey)
        .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 FarmRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"INSERT INTO farm_account (
                        "pool",
                        "tokens",
                        "token_accounts",
                        "supply",
                        "supply_left",
                        "accumulated_seconds_per_share",
                        "offset_seconds_per_share",
                        "start_time",
                        "end_time",
                        "last_update",
                        "bump",
                        "farm_type",
                                    __pubkey, __slot
                    ) VALUES (
                                                                        $1,                        $2,                        $3,                        $4,                        $5,                        $6,                        $7,                        $8,                        $9,                        $10,                        $11,                        $12,                        $13,                        $14                    ) ON CONFLICT (
                        __pubkey
                    ) DO UPDATE SET
                        "pool" = EXCLUDED."pool",
                        "tokens" = EXCLUDED."tokens",
                        "token_accounts" = EXCLUDED."token_accounts",
                        "supply" = EXCLUDED."supply",
                        "supply_left" = EXCLUDED."supply_left",
                        "accumulated_seconds_per_share" = EXCLUDED."accumulated_seconds_per_share",
                        "offset_seconds_per_share" = EXCLUDED."offset_seconds_per_share",
                        "start_time" = EXCLUDED."start_time",
                        "end_time" = EXCLUDED."end_time",
                        "last_update" = EXCLUDED."last_update",
                        "bump" = EXCLUDED."bump",
                        "farm_type" = EXCLUDED."farm_type",
                                    __slot = EXCLUDED.__slot
                    "#)
                .bind(self.pool)
                .bind(self.tokens.clone())
                .bind(self.token_accounts.clone())
                .bind(self.supply.clone())
                .bind(self.supply_left.clone())
                .bind(self.accumulated_seconds_per_share.clone())
                .bind(self.offset_seconds_per_share.clone())
                .bind(self.start_time.clone())
                .bind(self.end_time.clone())
                .bind(self.last_update.clone())
                .bind(self.bump)
                .bind(self.farm_type.clone())
                        .bind(self.metadata.pubkey)
        .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 FarmRow {
    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 farm_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 FarmRow {
    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 farm_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 FarmMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for FarmMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS farm_account (
                        -- Account data
                                    "pool" BYTEA NOT NULL,
                        "tokens" BYTEA[] NOT NULL,
                        "token_accounts" BYTEA[] NOT NULL,
                        "supply" JSONB NOT NULL,
                        "supply_left" JSONB NOT NULL,
                        "accumulated_seconds_per_share" JSONB NOT NULL,
                        "offset_seconds_per_share" JSONB NOT NULL,
                        "start_time" NUMERIC(20) NOT NULL,
                        "end_time" NUMERIC(20) NOT NULL,
                        "last_update" NUMERIC(20) NOT NULL,
                        "bump" INT2 NOT NULL,
                        "farm_type" 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 farm_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}
