#![allow(unused_imports, dead_code)]

pub mod common;

pub use common::{TestContext, features::*, setup::*};
use pretty_assertions::assert_eq;
use sea_orm::{DatabaseConnection, DerivePartialModel, QueryOrder, entity::prelude::*, entity::*};
use serde_json::json;

#[sea_orm_macros::test]
#[cfg(all(feature = "sqlx-postgres", feature = "postgres-array"))]
fn main() -> Result<(), DbErr> {
    let ctx = TestContext::new("collection_tests");
    create_tea_enum(&ctx.db)?;
    create_collection_table(&ctx.db)?;
    insert_collection(&ctx.db)?;
    update_collection(&ctx.db)?;
    select_collection(&ctx.db)?;
    ctx.delete();

    Ok(())
}

pub fn insert_collection(db: &DatabaseConnection) -> Result<(), DbErr> {
    use collection::*;

    let uuid = Uuid::new_v4();

    assert_eq!(
        Model {
            id: 1,
            name: "Collection 1".into(),
            integers: vec![1, 2, 3],
            integers_opt: Some(vec![1, 2, 3]),
            teas: vec![Tea::BreakfastTea],
            teas_opt: Some(vec![Tea::BreakfastTea]),
            colors: vec![Color::Black],
            colors_opt: Some(vec![Color::Black]),
            uuid: vec![uuid],
            uuid_hyphenated: vec![uuid.hyphenated()],
        }
        .into_active_model()
        .insert(db)?,
        Model {
            id: 1,
            name: "Collection 1".into(),
            integers: vec![1, 2, 3],
            integers_opt: Some(vec![1, 2, 3]),
            teas: vec![Tea::BreakfastTea],
            teas_opt: Some(vec![Tea::BreakfastTea]),
            colors: vec![Color::Black],
            colors_opt: Some(vec![Color::Black]),
            uuid: vec![uuid],
            uuid_hyphenated: vec![uuid.hyphenated()],
        }
    );

    assert_eq!(
        Model {
            id: 2,
            name: "Collection 2".into(),
            integers: vec![10, 9],
            integers_opt: None,
            teas: vec![Tea::BreakfastTea, Tea::AfternoonTea],
            teas_opt: None,
            colors: vec![Color::Black],
            colors_opt: None,
            uuid: vec![uuid],
            uuid_hyphenated: vec![uuid.hyphenated()],
        }
        .into_active_model()
        .insert(db)?,
        Model {
            id: 2,
            name: "Collection 2".into(),
            integers: vec![10, 9],
            integers_opt: None,
            teas: vec![Tea::BreakfastTea, Tea::AfternoonTea],
            teas_opt: None,
            colors: vec![Color::Black],
            colors_opt: None,
            uuid: vec![uuid],
            uuid_hyphenated: vec![uuid.hyphenated()],
        }
    );

    assert_eq!(
        Model {
            id: 3,
            name: "Collection 3".into(),
            integers: vec![],
            integers_opt: Some(vec![]),
            teas: vec![],
            teas_opt: Some(vec![]),
            colors: vec![],
            colors_opt: Some(vec![]),
            uuid: vec![uuid],
            uuid_hyphenated: vec![uuid.hyphenated()],
        }
        .into_active_model()
        .insert(db)?,
        Model {
            id: 3,
            name: "Collection 3".into(),
            integers: vec![],
            integers_opt: Some(vec![]),
            teas: vec![],
            teas_opt: Some(vec![]),
            colors: vec![],
            colors_opt: Some(vec![]),
            uuid: vec![uuid],
            uuid_hyphenated: vec![uuid.hyphenated()],
        }
    );

    assert_eq!(
        Entity::find_by_id(1).into_json().one(db)?,
        Some(json!({
            "id": 1,
            "name": "Collection 1",
            "integers": [1, 2, 3],
            "integers_opt": [1, 2, 3],
            "teas": ["BreakfastTea"],
            "teas_opt": ["BreakfastTea"],
            "colors": [0],
            "colors_opt": [0],
            "uuid": [uuid],
            "uuid_hyphenated": [uuid.hyphenated()],
        }))
    );

    assert_eq!(
        Entity::find_by_id(2).into_json().one(db)?,
        Some(json!({
            "id": 2,
            "name": "Collection 2",
            "integers": [10, 9],
            "integers_opt": null,
            "teas": ["BreakfastTea", "AfternoonTea"],
            "teas_opt": null,
            "colors": [0],
            "colors_opt": null,
            "uuid": [uuid],
            "uuid_hyphenated": [uuid.hyphenated()],
        }))
    );

    assert_eq!(
        Entity::find_by_id(3).into_json().one(db)?,
        Some(json!({
            "id": 3,
            "name": "Collection 3",
            "integers": [],
            "integers_opt": [],
            "teas": [],
            "teas_opt": [],
            "colors": [],
            "colors_opt": [],
            "uuid": [uuid],
            "uuid_hyphenated": [uuid.hyphenated()],
        }))
    );

    let found = Entity::find()
        .filter(Entity::COLUMN.teas.contains(vec![Tea::BreakfastTea]))
        .order_by_asc(Entity::COLUMN.id)
        .all(db)?;

    assert_eq!(found.len(), 2);
    assert_eq!(found[0].id, 1);
    assert_eq!(found[1].id, 2);

    let found = Entity::find()
        .filter(Entity::COLUMN.teas.contains(vec![Tea::AfternoonTea]))
        .order_by_asc(Entity::COLUMN.id)
        .all(db)?;

    assert_eq!(found.len(), 1);
    assert_eq!(found[0].id, 2);

    let found = Entity::find()
        .filter(
            Entity::COLUMN
                .teas
                .overlap(vec![Tea::BreakfastTea, Tea::AfternoonTea]),
        )
        .order_by_asc(Entity::COLUMN.id)
        .all(db)?;

    assert_eq!(found.len(), 2);
    assert_eq!(found[0].id, 1);
    assert_eq!(found[1].id, 2);

    let found = Entity::find()
        .filter(Entity::COLUMN.integers.contains(vec![10]))
        .order_by_asc(Entity::COLUMN.id)
        .all(db)?;

    assert_eq!(found.len(), 1);
    assert_eq!(found[0].id, 2);

    Ok(())
}

pub fn update_collection(db: &DatabaseConnection) -> Result<(), DbErr> {
    use collection::*;

    let uuid = Uuid::new_v4();
    let model = Entity::find_by_id(1).one(db)?.unwrap();

    ActiveModel {
        integers: Set(vec![4, 5, 6]),
        integers_opt: Set(Some(vec![4, 5, 6])),
        teas: Set(vec![Tea::EverydayTea]),
        teas_opt: Set(Some(vec![Tea::EverydayTea])),
        colors: Set(vec![Color::White]),
        colors_opt: Set(Some(vec![Color::White])),
        ..model.into_active_model()
    }
    .update(db)?;

    ActiveModel {
        id: Unchanged(3),
        name: Set("Collection 3".into()),
        integers: Set(vec![3, 1, 4]),
        integers_opt: Set(None),
        teas: Set(vec![Tea::EverydayTea]),
        teas_opt: Set(None),
        colors: Set(vec![Color::White]),
        colors_opt: Set(None),
        uuid: Set(vec![uuid]),
        uuid_hyphenated: Set(vec![uuid.hyphenated()]),
    }
    .update(db)?;

    Ok(())
}

pub fn select_collection(db: &DatabaseConnection) -> Result<(), DbErr> {
    use collection::*;

    #[derive(DerivePartialModel, Debug, PartialEq)]
    #[sea_orm(entity = "Entity")]
    struct PartialSelectResult {
        name: String,
    }

    let result = Entity::find_by_id(1)
        .into_partial_model::<PartialSelectResult>()
        .one(db)?;

    assert_eq!(
        result,
        Some(PartialSelectResult {
            name: "Collection 1".into(),
        })
    );

    Ok(())
}
