use loco_rs::prelude::*;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set};

use crate::{
    models::shipping_methods,
    shared::settings,
};

pub fn packeta_ready(ctx: &AppContext) -> bool {
    ["packeta_api_key", "packeta_api_password", "packeta_sender_label"]
        .iter()
        .all(|key| settings::get(ctx, key).is_some_and(|value| !value.trim().is_empty()))
}

pub async fn disable_packeta_if_unconfigured(ctx: &AppContext) -> Result<()> {
    if packeta_ready(ctx) {
        return Ok(());
    }
    let Some(method) = shipping_methods::Entity::find()
        .filter(shipping_methods::Column::Carrier.eq("packeta"))
        .filter(shipping_methods::Column::Enabled.eq(true))
        .one(&ctx.db)
        .await?
    else {
        return Ok(());
    };
    let mut active = method.into_active_model();
    active.enabled = Set(false);
    active.update(&ctx.db).await?;
    Ok(())
}
