use serde::Serialize;
use sqlx::{sqlite::SqliteQueryResult, FromRow, SqlitePool};

use super::user::User;

#[derive(FromRow, Serialize, Clone)]
pub struct Family {
    id: i64,
}

#[derive(Serialize, Clone)]
pub struct FamilyWithMembers {
    id: i64,
    names: Option<String>,
}

impl Family {
    pub async fn all(db: &SqlitePool) -> Vec<Self> {
        sqlx::query_as!(Self, "SELECT id FROM role")
            .fetch_all(db)
            .await
            .unwrap()
    }

    pub async fn insert(db: &SqlitePool) -> i64 {
        let result: SqliteQueryResult = sqlx::query("INSERT INTO family DEFAULT VALUES")
            .execute(db)
            .await
            .unwrap();

        result.last_insert_rowid()
    }

    pub async fn all_with_members(db: &SqlitePool) -> Vec<FamilyWithMembers> {
        sqlx::query_as!(
            FamilyWithMembers,
            "
SELECT
    family.id as id,
    GROUP_CONCAT(user.name, ', ') as names
FROM family
LEFT JOIN
    user ON family.id = user.family_id
GROUP BY family.id;"
        )
        .fetch_all(db)
        .await
        .unwrap()
    }

    pub async fn find_by_id(db: &SqlitePool, id: i64) -> Option<Self> {
        sqlx::query_as!(Self, "SELECT id FROM family WHERE id like ?", id)
            .fetch_one(db)
            .await
            .ok()
    }

    pub async fn find_by_opt_id(db: &SqlitePool, id: Option<i64>) -> Option<Self> {
        if let Some(id) = id {
            Self::find_by_id(db, id).await
        } else {
            None
        }
    }

    pub async fn amount_family_members(&self, db: &SqlitePool) -> i32 {
        sqlx::query!(
            "SELECT COUNT(*) as count FROM user WHERE family_id = ?",
            self.id
        )
        .fetch_one(db)
        .await
        .unwrap()
        .count
    }

    pub async fn members(&self, db: &SqlitePool) -> Vec<User> {
        sqlx::query_as!(User, "SELECT id, name, pw, deleted, last_access, dob, weight, sex, member_since_date, birthdate, mail, nickname, notes, phone, address, family_id FROM user WHERE family_id = ?", self.id)
            .fetch_all(db)
            .await
            .unwrap()
    }
}
