//! 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::Provider;
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 ProviderRow {
    #[sqlx(flatten)]
    pub metadata: AccountRowMetadata,
    pub token_x: Pubkey,
    pub token_y: Pubkey,
    pub owner: Pubkey,
    pub shares: sqlx::types::Json<Token>,
    pub last_fee_accumulator_x: sqlx::types::Json<FixedPoint>,
    pub last_fee_accumulator_y: sqlx::types::Json<FixedPoint>,
    pub last_seconds_per_share: sqlx::types::Json<FixedPoint>,
    pub last_withdraw_time: U64,
    pub tokens_owed_x: sqlx::types::Json<Token>,
    pub tokens_owed_y: sqlx::types::Json<Token>,
    pub current_farm_count: U64,
    pub bump: U8,
}

impl ProviderRow {
    pub fn from_parts(source: Provider, metadata: AccountMetadata) -> Self {
        Self {
            metadata: metadata.into(),
            token_x: source.token_x.into(),
            token_y: source.token_y.into(),
            owner: source.owner.into(),
            shares: sqlx::types::Json(source.shares),
            last_fee_accumulator_x: sqlx::types::Json(source.last_fee_accumulator_x),
            last_fee_accumulator_y: sqlx::types::Json(source.last_fee_accumulator_y),
            last_seconds_per_share: sqlx::types::Json(source.last_seconds_per_share),
            last_withdraw_time: source.last_withdraw_time.into(),
            tokens_owed_x: sqlx::types::Json(source.tokens_owed_x),
            tokens_owed_y: sqlx::types::Json(source.tokens_owed_y),
            current_farm_count: source.current_farm_count.into(),
            bump: source.bump.into(),
        }
    }
}

impl TryFrom<ProviderRow> for Provider {
    type Error = carbon_core::error::Error;
    fn try_from(source: ProviderRow) -> Result<Self, Self::Error> {
        Ok(Self {
            token_x: *source.token_x,
            token_y: *source.token_y,
            owner: *source.owner,
            shares: source.shares.0,
            last_fee_accumulator_x: source.last_fee_accumulator_x.0,
            last_fee_accumulator_y: source.last_fee_accumulator_y.0,
            last_seconds_per_share: source.last_seconds_per_share.0,
            last_withdraw_time: *source.last_withdraw_time,
            tokens_owed_x: source.tokens_owed_x.0,
            tokens_owed_y: source.tokens_owed_y.0,
            current_farm_count: *source.current_farm_count,
            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 Provider {
    fn table() -> &'static str {
        "provider_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "token_x",
            "token_y",
            "owner",
            "shares",
            "last_fee_accumulator_x",
            "last_fee_accumulator_y",
            "last_seconds_per_share",
            "last_withdraw_time",
            "tokens_owed_x",
            "tokens_owed_y",
            "current_farm_count",
            "bump",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for ProviderRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"
            INSERT INTO provider_account (
                            "token_x",
                            "token_y",
                            "owner",
                            "shares",
                            "last_fee_accumulator_x",
                            "last_fee_accumulator_y",
                            "last_seconds_per_share",
                            "last_withdraw_time",
                            "tokens_owed_x",
                            "tokens_owed_y",
                            "current_farm_count",
                            "bump",
                                        __pubkey, __slot
                        ) VALUES (
                                                                            $1,                            $2,                            $3,                            $4,                            $5,                            $6,                            $7,                            $8,                            $9,                            $10,                            $11,                            $12,                            $13,                            $14                    )"#)
                .bind(self.token_x)
                .bind(self.token_y)
                .bind(self.owner)
                .bind(self.shares.clone())
                .bind(self.last_fee_accumulator_x.clone())
                .bind(self.last_fee_accumulator_y.clone())
                .bind(self.last_seconds_per_share.clone())
                .bind(self.last_withdraw_time.clone())
                .bind(self.tokens_owed_x.clone())
                .bind(self.tokens_owed_y.clone())
                .bind(self.current_farm_count.clone())
                .bind(self.bump)
                        .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 ProviderRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(r#"INSERT INTO provider_account (
                        "token_x",
                        "token_y",
                        "owner",
                        "shares",
                        "last_fee_accumulator_x",
                        "last_fee_accumulator_y",
                        "last_seconds_per_share",
                        "last_withdraw_time",
                        "tokens_owed_x",
                        "tokens_owed_y",
                        "current_farm_count",
                        "bump",
                                    __pubkey, __slot
                    ) VALUES (
                                                                        $1,                        $2,                        $3,                        $4,                        $5,                        $6,                        $7,                        $8,                        $9,                        $10,                        $11,                        $12,                        $13,                        $14                    ) ON CONFLICT (
                        __pubkey
                    ) DO UPDATE SET
                        "token_x" = EXCLUDED."token_x",
                        "token_y" = EXCLUDED."token_y",
                        "owner" = EXCLUDED."owner",
                        "shares" = EXCLUDED."shares",
                        "last_fee_accumulator_x" = EXCLUDED."last_fee_accumulator_x",
                        "last_fee_accumulator_y" = EXCLUDED."last_fee_accumulator_y",
                        "last_seconds_per_share" = EXCLUDED."last_seconds_per_share",
                        "last_withdraw_time" = EXCLUDED."last_withdraw_time",
                        "tokens_owed_x" = EXCLUDED."tokens_owed_x",
                        "tokens_owed_y" = EXCLUDED."tokens_owed_y",
                        "current_farm_count" = EXCLUDED."current_farm_count",
                        "bump" = EXCLUDED."bump",
                                    __slot = EXCLUDED.__slot
                    "#)
                .bind(self.token_x)
                .bind(self.token_y)
                .bind(self.owner)
                .bind(self.shares.clone())
                .bind(self.last_fee_accumulator_x.clone())
                .bind(self.last_fee_accumulator_y.clone())
                .bind(self.last_seconds_per_share.clone())
                .bind(self.last_withdraw_time.clone())
                .bind(self.tokens_owed_x.clone())
                .bind(self.tokens_owed_y.clone())
                .bind(self.current_farm_count.clone())
                .bind(self.bump)
                        .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 ProviderRow {
    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 provider_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 ProviderRow {
    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 provider_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 ProviderMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for ProviderMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS provider_account (
                        -- Account data
                                    "token_x" BYTEA NOT NULL,
                        "token_y" BYTEA NOT NULL,
                        "owner" BYTEA NOT NULL,
                        "shares" JSONB NOT NULL,
                        "last_fee_accumulator_x" JSONB NOT NULL,
                        "last_fee_accumulator_y" JSONB NOT NULL,
                        "last_seconds_per_share" JSONB NOT NULL,
                        "last_withdraw_time" NUMERIC(20) NOT NULL,
                        "tokens_owed_x" JSONB NOT NULL,
                        "tokens_owed_y" JSONB NOT NULL,
                        "current_farm_count" NUMERIC(20) NOT NULL,
                        "bump" INT2 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 provider_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}
