use crate::{
    DataManager, auto_method,
    model::{
        Error, Result,
        groups::{GroupSettings, GroupMembership, Group, GroupRole},
        id::Id,
    },
};
use oiseau::query_rows;
use oiseau::{PostgresRow, cache::Cache, execute, get, params, query_row};

impl DataManager {
    /// Get a [`Group`] from an SQL row.
    pub(crate) fn get_group_from_row(x: &PostgresRow) -> Group {
        Group {
            id: Id::deserialize(&get!(x->0(String))),
            created: get!(x->1(i64)) as u128,
            owner: Id::deserialize(&get!(x->2(String))),
            name: get!(x->3(String)),
            settings: serde_json::from_str(&get!(x->4(String))).unwrap(),
            members: get!(x->5(i32)),
        }
    }

    auto_method!(get_group_by_id()@get_group_from_row -> "SELECT * FROM groups WHERE id = $1" --name="group" --returns=Group --cache-key-tmpl="atto.group:{}");
    auto_method!(get_group_by_name(&str)@get_group_from_row -> "SELECT * FROM groups WHERE name = $1" --name="group" --returns=Group --cache-key-tmpl="atto.group:{}");

    /// Get groups by a search query.
    pub async fn get_groups_searched(
        &self,
        query: &str,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Group>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM groups WHERE name LIKE $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[
                &format!("%{query}%"),
                &(batch as i64),
                &((page * batch) as i64)
            ],
            |x| { Self::get_group_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("group".to_string()));
        }

        Ok(res.unwrap())
    }

    /// Create a new group in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Group`] object to insert
    pub async fn create_group(&self, mut data: Group) -> Result<Id> {
        data.name = data.name.to_lowercase();

        // check for existing
        if self.get_group_by_name(&data.name).await.is_ok() {
            return Err(Error::MiscError("Name is already in use".to_string()));
        }

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "INSERT INTO groups VALUES ($1, $2, $3, $4, $5, $6)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &data.owner.printable(),
                &data.name,
                &serde_json::to_string(&data.settings).unwrap(),
                &data.members,
            ]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        // create membership
        self.create_group_membership(GroupMembership::new(
            data.owner,
            data.id.clone(),
            GroupRole::Owner,
        ))
        .await?;

        // return
        Ok(data.id)
    }

    pub async fn update_group_settings(&self, id: &Id, settings: GroupSettings) -> Result<()> {
        let y = self.get_group_by_id(id).await?;

        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "UPDATE groups SET settings = $1 WHERE id = $2",
            &[&serde_json::to_string(&settings).unwrap(), &id.printable()]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        self.cache_clear_group(&y).await;

        // return
        Ok(())
    }

    pub async fn update_group_owner(&self, id: &Id, owner: Id) -> Result<()> {
        let y = self.get_group_by_id(id).await?;

        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "UPDATE groups SET owner = $1 WHERE id = $2",
            &[&owner.printable(), &id.printable()]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        self.cache_clear_group(&y).await;

        // return
        Ok(())
    }

    pub async fn delete_group(&self, id: &Id) -> Result<()> {
        let y = self.get_group_by_id(id).await?;

        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "DELETE FROM groups WHERE id = $1",
            &[&id.printable()]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        self.cache_clear_group(&y).await;

        // delete images
        if let Ok(avatar) = self
            .1
            .get_upload_by_id_bucket(id.as_usize(), "group_avatars")
            .await
            && let Err(e) = self
                .1
                .delete_upload_with_bucket(avatar.id, "group_avatars")
                .await
            {
                return Err(Error::MiscError(e.to_string()));
            }

        if let Ok(banner) = self
            .1
            .get_upload_by_id_bucket(id.as_usize(), "group_banners")
            .await
            && let Err(e) = self
                .1
                .delete_upload_with_bucket(banner.id, "group_banners")
                .await
            {
                return Err(Error::MiscError(e.to_string()));
            }

        // return
        Ok(())
    }

    pub async fn cache_clear_group(&self, c: &Group) -> bool {
        self.0.1.remove(format!("atto.group:{}", c.id)).await
            && self.0.1.remove(format!("atto.group:{}", c.name)).await
    }

    auto_method!(incr_group_members()@get_group_by_id -> "UPDATE groups SET members = members + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_group --incr);
    auto_method!(decr_group_members()@get_group_by_id -> "UPDATE groups SET members = members - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_group --decr=members);
}
