use crate::db;
use serde::{Deserialize, Serialize};

#[derive(sqlx::FromRow, Serialize, Deserialize)]
pub struct CustomLabel {
    custom_label_id: i32,
    custom_label_value: String,
}

impl CustomLabel {
    pub async fn get_all() -> Result<Vec<CustomLabel>, sqlx::Error> {
        let db = db();

        let result = sqlx::query_as::<_, CustomLabel>(
            r#"
            SELECT custom_label_id, custom_label_value
            FROM custom_label
            "#,
        )
        .fetch_all(db)
        .await?;

        Ok(result)
    }

    pub async fn get_id_by_value(value: &String) -> Result<i32, sqlx::Error> {
        let db = db();

        let result = sqlx::query!(
            "SELECT custom_label_id FROM custom_label WHERE custom_label_value = ?",
            value
        )
        .fetch_all(db)
        .await?;

        if result.is_empty() {
            Ok(-1)
        } else {
            let id = &result[0].custom_label_id;

            Ok(*id)
        }
    }

    pub async fn create(value: &String) -> Result<i32, sqlx::Error> {
        let db = db();

        sqlx::query!(
            "INSERT INTO custom_label (custom_label_value) VALUES (?)",
            value
        )
        .execute(db)
        .await?;
        let result = Self::get_id_by_value(value).await?;

        Ok(result)
    }
}
