pub use crate::models::_entities::account_cart_items::{ActiveModel, Column, Entity, Model};
use sea_orm::entity::prelude::*;
use sea_orm::{ActiveValue, QueryFilter, QueryOrder};

pub type AccountCartItems = Entity;

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C>(self, _db: &C, _insert: bool) -> std::result::Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        Ok(self)
    }
}

impl Model {
    pub async fn find_for_user(
        db: &DatabaseConnection,
        user_id: i32,
    ) -> Result<Vec<(i32, i32)>, DbErr> {
        Ok(Entity::find()
            .filter(Column::UserId.eq(user_id))
            .order_by_asc(Column::Id)
            .all(db)
            .await?
            .into_iter()
            .filter_map(|item| (item.quantity > 0).then_some((item.variant_id, item.quantity)))
            .collect())
    }

    pub async fn replace_for_user(
        db: &DatabaseConnection,
        user_id: i32,
        items: &[(i32, i32)],
    ) -> Result<(), DbErr> {
        Entity::delete_many()
            .filter(Column::UserId.eq(user_id))
            .exec(db)
            .await?;

        for (variant_id, quantity) in items.iter().copied().filter(|(_, qty)| *qty > 0) {
            ActiveModel {
                user_id: ActiveValue::set(user_id),
                variant_id: ActiveValue::set(variant_id),
                quantity: ActiveValue::set(quantity),
                ..Default::default()
            }
            .insert(db)
            .await?;
        }

        Ok(())
    }
}
