use log::{error, info};
use serde::{Deserialize, Serialize};
use sqlx::{Arguments, AssertSqlSafe, FromRow, PgPool, Row};
use sqlx::postgres::{PgArguments, PgRow};
use crate::models::label::{load_label, Label};
use crate::models::unit::Unit;

#[derive(Debug, Deserialize, Serialize, Clone, FromRow)]
pub struct Variant {
    pub id: i64,
    pub weight: String,
    pub ean: Option<String>,
    pub name: Option<String>,
    pub description: Option<String>,
    pub ingredients: Option<String>,
    pub unit: Unit,
    pub label: Option<Label>,
    pub variant_description: Option<String>,
    pub topm_row: Option<String>,
}

async fn from_postgres_row(row: PgRow, pool: &PgPool) -> Variant {
    let label_id_option: Option<i64> = row.get(8);
    let label: Option<Label> = match label_id_option {
        Some(label_id) => {
            load_label(label_id, pool).await
        }
        None => {
            None
        }
    };

    Variant {
        id: row.get(0),
        weight: row.get(2),
        ean: row.get(3),
        name: row.get(4),
        description: row.get(5),
        ingredients: row.get(6),
        unit: row.get(7),
        label: label,
        variant_description: row.get(9),
        topm_row: row.get(10),
    }
}

pub async fn load_article_variants(article_id: i64, pool: &PgPool) -> Option<Vec<Variant>> {
    let statement = format!(
        "SELECT * FROM {} WHERE article_id = $1",
        "variant",
    );

    let mut args = PgArguments::default();
    args.add(article_id);

    let res = sqlx::query_with(
        AssertSqlSafe(statement.as_str()), args)
        .fetch_all(pool).await;

    let mut variants: Vec<Variant> = Vec::new();

    match res {
        Ok(records) => {
            for record in records {
                variants.push(
                    from_postgres_row(record, &pool).await
                );
            }

            Some(variants)
        }
        Err(err) => {
            error!("Error while loading variants for article: {}", article_id);
            None
        }
    }
}

pub async fn insert_variant(article_id: i64, variant: &Variant, pool: PgPool) -> Option<Variant> {
    let label_id = match &variant.label {
        Some(label) => {
            Some(label.id)
        }
        None => {
            None
        }
    };

    let mut args = PgArguments::default();
    args.add(&article_id);
    args.add(&variant.weight);
    args.add(&variant.ean);
    args.add(&variant.name);
    args.add(&variant.description);
    args.add(&variant.ingredients);
    args.add(&variant.unit);
    args.add(label_id);
    args.add(&variant.variant_description);
    args.add(&variant.topm_row);

    let statement = format!(
        "INSERT INTO {} (article_id, weight, ean, name, description, ingredients, unit_id, label_id, variant_description, topm_row) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *",
        "variant",
    );

    let res = sqlx::query_with(
        AssertSqlSafe(statement.as_str()),
        args)
        .fetch_one(&pool).await;

    info!("{:#?}", res);

    match res {
        Ok(record) => {
            let variant = from_postgres_row(record, &pool).await;
            Some(variant)
        }
        Err(err) => {
            error!("Error while loading newly created variant for article: {}", article_id);
            None
        }
    }
}

pub async fn update_variant(variant_id: i64, variant: &Variant, pool: PgPool) -> Option<Variant> {
    let label_id = match &variant.label {
        Some(label) => {
            Some(label.id)
        }
        None => {
            None
        }
    };

    let mut args = PgArguments::default();
    args.add(&variant.id);
    args.add(&variant.weight);
    args.add(&variant.ean);
    args.add(&variant.name);
    args.add(&variant.description);
    args.add(&variant.ingredients);
    args.add(&variant.unit);
    args.add(label_id);
    args.add(&variant.variant_description);
    args.add(&variant.topm_row);

    info!("Variant: {:#?}", variant);

    let statement = format!(
        "UPDATE {} SET weight = $2, ean = $3, name = $4, description = $5, ingredients = $6, unit_id = $7, label_id = $8, variant_description = $9, topm_row = $10 WHERE id = $1 RETURNING *",
        "variant",
    );

    let res = sqlx::query_with(
        AssertSqlSafe(statement.as_str()),
        args)
        .fetch_one(&pool).await;

    info!("{:#?}", res);

    match res {
        Ok(record) => {
            let variant = from_postgres_row(record, &pool).await;
            Some(variant)
        }
        Err(err) => {
            error!("Error while updating variant: {}", variant_id);
            None
        }
    }
}

pub async fn delete_variant(variant_id: i64, pool: PgPool) -> Option<()> {
    let result = sqlx::query(
        AssertSqlSafe(format!("DELETE FROM {} WHERE id = {}",
                "variant",
                variant_id
        ).as_str())
    ).execute(&pool).await;

    match result {
        Ok(_) => {
            Some(())
        }
        Err(err) => {
            println!("Error deleting variant: {:#?}", err);

            None
        }
    }
}
