use std::sync::Arc;

use sea_orm::{DatabaseConnection, EntityTrait};
use serde::Serialize;

use crate::models::{
    menu_cate,
    menu_commodity::{self},
    prelude::{MenuCate, MenuCommodity},
};

pub struct Category {
    conn: Arc<DatabaseConnection>,
}

#[derive(Debug, Serialize)]
pub struct CategoryWithSpu {
    #[serde(flatten)]
    pub category: menu_cate::Model,
    pub goods: Vec<menu_commodity::Model>,
}

impl Category {
    pub fn new(conn: Arc<DatabaseConnection>) -> Self {
        return Self { conn };
    }
    pub async fn get_category_commodity(&self) -> anyhow::Result<Vec<CategoryWithSpu>> {
        let categories_with_goods: Vec<(menu_cate::Model, Vec<menu_commodity::Model>)> =
            MenuCate::find()
                .find_with_related(MenuCommodity)
                .all(&*self.conn)
                .await?;

        Ok(categories_with_goods
            .into_iter()
            .map(|(category, goods)| CategoryWithSpu { category, goods })
            .collect())
    }
}
