use oiseau::cache::Cache;
use crate::model::{
    Error, Result,
    addr::RemoteAddr,
    auth::{AchievementName, Notification, User},
    id::Id,
    permissions::FinePermission,
    reactions::{AssetType, Reaction},
};
use crate::{auto_method, DataManager};
use oiseau::{PostgresRow, execute, get, query_row, query_rows, params};

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

    auto_method!(get_reaction_by_id()@get_reaction_from_row -> "SELECT * FROM reactions WHERE id = $1" --name="reaction" --returns=Reaction --cache-key-tmpl="atto.reaction:{}");

    /// Get all owner profiles from a reactions list.
    pub async fn fill_reactions(
        &self,
        reactions: &Vec<Reaction>,
        ignore_users: Vec<Id>,
    ) -> Result<Vec<(Reaction, User)>> {
        let mut out = Vec::new();

        for reaction in reactions {
            if ignore_users.contains(&reaction.owner) {
                continue;
            }

            out.push((
                reaction.to_owned(),
                self.get_user_by_id(&reaction.owner).await?,
            ));
        }

        Ok(out)
    }

    /// Get all reactions by their `asset`.
    pub async fn get_reactions_by_asset(
        &self,
        asset: usize,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Reaction>> {
        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 reactions WHERE asset = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[&(asset as i64), &(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_reaction_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all reactions (likes only) by their `asset`.
    pub async fn get_likes_reactions_by_asset(
        &self,
        asset: usize,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Reaction>> {
        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 reactions WHERE asset = $1 AND is_like = 1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[&(asset as i64), &(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_reaction_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get a reaction by `owner` and `asset`.
    pub async fn get_reaction_by_owner_asset(&self, owner: &Id, asset: &Id) -> Result<Reaction> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_row!(
            &conn,
            "SELECT * FROM reactions WHERE owner = $1 AND asset = $2",
            &[&owner.printable(), &asset.printable()],
            |x| { Ok(Self::get_reaction_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Create a new reaction in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Reaction`] object to insert
    pub async fn create_reaction(
        &self,
        data: Reaction,
        user: &User,
        addr: &RemoteAddr,
    ) -> Result<()> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        if data.asset_type == AssetType::Post {
            let post = self.get_post_by_id(&data.asset).await?;

            if (self
                .get_user_block_by_initiator_receiver(&post.owner, &user.id)
                .await
                .is_ok()
                | self
                    .get_ip_block_by_initiator_receiver(&post.owner, addr)
                    .await
                    .is_ok())
                && !user.permissions.check(FinePermission::ManagePosts)
            {
                return Err(Error::NotAllowed);
            }

            // achievements
            if user.id != post.owner {
                let mut owner = self.get_user_by_id(&post.owner).await?;
                self.add_achievement(&mut owner, AchievementName::Get1Like.into(), true)
                    .await?;

                if post.likes >= 9 {
                    self.add_achievement(&mut owner, AchievementName::Get10Likes.into(), true)
                        .await?;
                }

                if post.likes >= 49 {
                    self.add_achievement(&mut owner, AchievementName::Get50Likes.into(), true)
                        .await?;
                }

                if post.likes >= 99 {
                    self.add_achievement(&mut owner, AchievementName::Get100Likes.into(), true)
                        .await?;
                }

                if post.dislikes >= 24 {
                    self.add_achievement(&mut owner, AchievementName::Get25Dislikes.into(), true)
                        .await?;
                }
            }
        } else if data.asset_type == AssetType::Question {
            let question = self.get_question_by_id(&data.asset).await?;

            if self
                .get_user_block_by_initiator_receiver(&question.owner, &user.id)
                .await
                .is_ok()
                && !user.permissions.check(FinePermission::ManagePosts)
            {
                return Err(Error::NotAllowed);
            }
        }

        // ...
        let res = execute!(
            &conn,
            "INSERT INTO reactions VALUES ($1, $2, $3, $4, $5, $6)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &data.owner.printable(),
                &data.asset.printable(),
                &serde_json::to_string(&data.asset_type).unwrap().as_str(),
                &if data.is_like { 1 } else { 0 }
            ]
        );

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

        // incr corresponding
        match data.asset_type {
            AssetType::Post => {
                if let Err(e) = {
                    if data.is_like {
                        self.incr_post_likes(&data.asset).await
                    } else {
                        self.incr_post_dislikes(&data.asset).await
                    }
                } {
                    return Err(e);
                } else if data.is_like {
                    let post = self.get_post_by_id(&data.asset).await.unwrap();

                    if post.owner != user.id {
                        self.create_notification(Notification::new(
                            "Your post has received a like!".to_string(),
                            format!(
                                "[@{}](/api/v2/users/find/{}) has liked your [post](/posts/{})!",
                                user.username, user.id, data.asset
                            ),
                            post.owner,
                        ))
                        .await?
                    }
                }
            }
            AssetType::Question => {
                if let Err(e) = {
                    if data.is_like {
                        self.incr_question_likes(&data.asset).await
                    } else {
                        self.incr_question_dislikes(&data.asset).await
                    }
                } {
                    return Err(e);
                } else if data.is_like {
                    let question = self.get_question_by_id(&data.asset).await.unwrap();

                    if question.owner != user.id {
                        self
                            .create_notification(Notification::new(
                                "Your question has received a like!".to_string(),
                                format!(
                                    "[@{}](/api/v2/users/find/{}) has liked your [question](/questions/{})!",
                                    user.username, user.id, data.asset
                                ),
                                question.owner,
                            ))
                            .await?
                    }
                }
            }
            AssetType::Group => {
                return Err(Error::NotAllowed);
            }
            AssetType::User => {
                return Err(Error::NotAllowed);
            }
        };

        // return
        Ok(())
    }

    pub async fn delete_reaction(&self, id: &Id, user: &User) -> Result<()> {
        let reaction = self.get_reaction_by_id(id).await?;

        if user.id != reaction.owner && !user.permissions.check(FinePermission::ManageReactions) {
            return Err(Error::NotAllowed);
        }

        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 reactions WHERE id = $1",
            &[&id.printable()]
        );

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

        self.0.1.remove(format!("atto.reaction:{}", id)).await;

        // decr corresponding
        match reaction.asset_type {
            AssetType::Post => {
                if reaction.is_like {
                    self.decr_post_likes(&reaction.asset).await
                } else {
                    self.decr_post_dislikes(&reaction.asset).await
                }
            }?,
            AssetType::Question => {
                if reaction.is_like {
                    self.decr_question_likes(&reaction.asset).await
                } else {
                    self.decr_question_dislikes(&reaction.asset).await
                }
            }?,
            AssetType::Group => {
                return Err(Error::NotAllowed);
            }
            AssetType::User => {
                return Err(Error::NotAllowed);
            }
        };

        // return
        Ok(())
    }
}
