use sea_orm::entity::prelude::*;
use sea_orm::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, QueryOrder};

pub use crate::models::_entities::payment_methods::{ActiveModel, Column, Entity, Model};
pub type PaymentMethods = Entity;

pub const COD: &str = "cod";
pub const BANK_TRANSFER: &str = "bank_transfer";

#[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,
    {
        if !insert && self.updated_at.is_unchanged() {
            let mut this = self;
            this.updated_at = ActiveValue::set(chrono::Utc::now().into());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Entity {
    pub async fn enabled<C: ConnectionTrait>(db: &C) -> Result<Vec<Model>, DbErr> {
        Entity::find()
            .filter(Column::Enabled.eq(true))
            .order_by_asc(Column::Position)
            .all(db)
            .await
    }

    pub async fn find_enabled<C: ConnectionTrait>(db: &C, code: &str) -> Result<Option<Model>, DbErr> {
        Entity::find()
            .filter(Column::Code.eq(code))
            .filter(Column::Enabled.eq(true))
            .one(db)
            .await
    }
}

impl Model {
    pub fn label_key(&self) -> &'static str {
        match self.code.as_str() {
            COD => "payment-cod",
            BANK_TRANSFER => "payment-bank",
            _ => "payment-custom",
        }
    }
}

impl ActiveModel {}
