use oiseau::cache::Cache;
use crate::model::auth::AchievementName;
use crate::model::requests::{ActionRequest, ActionType};
use crate::model::{Error, Result, auth::User, auth::UserFollow, permissions::FinePermission, id::Id};
use crate::{auto_method, DataManager};

use oiseau::{PostgresRow, execute, get, query_row, query_rows, params};

impl DataManager {
    /// Get a [`UserFollow`] from an SQL row.
    pub(crate) fn get_user_follow_from_row(x: &PostgresRow) -> UserFollow {
        UserFollow {
            id: Id::deserialize(&get!(x->0(String))),
            created: get!(x->1(i64)) as u128,
            initiator: Id::deserialize(&get!(x->2(String))),
            receiver: Id::deserialize(&get!(x->3(String))),
        }
    }

    auto_method!(get_user_follow_by_id()@get_user_follow_from_row -> "SELECT * FROM user_follows WHERE id = $1" --name="user follow" --returns=UserFollow --cache-key-tmpl="atto.user_follow:{}");

    /// Filter to update user_follows to clean their users for public APIs.
    pub fn user_follows_user_filter(&self, x: &[(UserFollow, User)]) -> Vec<(UserFollow, User)> {
        let mut out: Vec<(UserFollow, User)> = Vec::new();

        for mut y in x.iter().cloned() {
            y.1.clean();
            out.push(y);
        }

        out
    }

    /// Get a user follow by `initiator` and `receiver` (in that order).
    pub async fn get_user_follow_by_initiator_receiver(
        &self,
        initiator: &Id,
        receiver: &Id,
    ) -> Result<UserFollow> {
        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 user_follows WHERE initiator = $1 AND receiver = $2",
            &[&initiator.printable(), &receiver.printable()],
            |x| { Ok(Self::get_user_follow_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Get a user follow by `receiver` and `initiator` (in that order).
    pub async fn get_user_follow_by_receiver_initiator(
        &self,
        receiver: &Id,
        initiator: &Id,
    ) -> Result<UserFollow> {
        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 user_follows WHERE receiver = $1 AND initiator = $2",
            &[&receiver.printable(), &initiator.printable()],
            |x| { Ok(Self::get_user_follow_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Get users the given user is following.
    ///
    /// # Arguments
    /// * `id` - the ID of the user
    /// * `batch` - the limit of user_follows in each page
    /// * `page` - the page number
    pub async fn get_user_follows_by_initiator(
        &self,
        id: &Id,
        batch: usize,
        page: usize,
    ) -> Result<Vec<UserFollow>> {
        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 user_follows WHERE initiator = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[&id.printable(), &(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_user_follow_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get users the given user is following.
    ///
    /// # Arguments
    /// * `id` - the ID of the user
    pub async fn get_user_follows_by_initiator_all(&self, id: &Id) -> Result<Vec<UserFollow>> {
        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 user_follows WHERE initiator = $1",
            &[&id.printable()],
            |x| { Self::get_user_follow_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get users following the given user.
    ///
    /// # Arguments
    /// * `id` - the ID of the user
    /// * `batch` - the limit of user_follows in each page
    /// * `page` - the page number
    pub async fn get_user_follows_by_receiver(
        &self,
        id: &Id,
        batch: usize,
        page: usize,
    ) -> Result<Vec<UserFollow>> {
        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 user_follows WHERE receiver = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[&id.printable(), &(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_user_follow_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get users following the given user.
    ///
    /// # Arguments
    /// * `id` - the ID of the user
    pub async fn get_user_follows_by_receiver_all(&self, id: &Id) -> Result<Vec<UserFollow>> {
        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 user_follows WHERE receiver = $1",
            &[&id.printable()],
            |x| { Self::get_user_follow_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Complete a vector of just user_follows with their receiver as well.
    pub async fn fill_user_follows_with_receiver(
        &self,
        user_follows: Vec<UserFollow>,
        as_user: &Option<User>,
        do_check: bool,
    ) -> Result<Vec<(UserFollow, User)>> {
        let mut out: Vec<(UserFollow, User)> = Vec::new();

        for userfollow in user_follows {
            let receiver = userfollow.receiver.clone();
            let user = match self.get_user_by_id(&receiver).await {
                Ok(u) => u,
                Err(_) => continue,
            };

            if user.settings.hide_from_social_lists && do_check {
                if let Some(ua) = as_user {
                    if !ua.permissions.check(FinePermission::ManageUsers) {
                        continue;
                    }
                } else {
                    continue;
                }
            }

            out.push((userfollow, user));
        }

        Ok(out)
    }

    /// Complete a vector of just user_follows with their initiator as well.
    pub async fn fill_user_follows_with_initiator(
        &self,
        user_follows: Vec<UserFollow>,
        as_user: &Option<User>,
        do_check: bool,
    ) -> Result<Vec<(UserFollow, User)>> {
        let mut out: Vec<(UserFollow, User)> = Vec::new();

        for userfollow in user_follows {
            let initiator = userfollow.initiator.clone();
            let user = match self.get_user_by_id(&initiator).await {
                Ok(u) => u,
                Err(_) => continue,
            };

            if user.settings.hide_from_social_lists && do_check {
                if let Some(ua) = as_user {
                    if !ua.permissions.check(FinePermission::ManageUsers) {
                        continue;
                    }
                } else {
                    continue;
                }
            }

            out.push((userfollow, user));
        }

        Ok(out)
    }

    /// Create a new user follow in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`UserFollow`] object to insert
    /// * `force` - if we should skip the request stage
    pub async fn create_user_follow(
        &self,
        data: UserFollow,
        initiator: &User,
        force: bool,
    ) -> Result<bool> {
        let mut asked = false;
        if !force {
            let mut other_user = self.get_user_by_id(&data.receiver).await?;

            if other_user.settings.private_profile {
                // send follow request
                self.create_request(ActionRequest::with_id(
                    data.initiator.clone(),
                    data.receiver.clone(),
                    ActionType::Follow,
                    data.receiver.clone(),
                    None,
                ))
                .await?;

                asked = true;
            }

            // check if we're staff
            if initiator.permissions.check(FinePermission::StaffBadge) {
                self.add_achievement(
                    &mut other_user,
                    AchievementName::FollowedByStaff.into(),
                    true,
                )
                .await?;
            }

            // other achivements
            self.add_achievement(&mut other_user, AchievementName::Get1Follower.into(), true)
                .await?;

            if other_user.follower_count >= 9 {
                self.add_achievement(
                    &mut other_user,
                    AchievementName::Get10Followers.into(),
                    true,
                )
                .await?;
            }

            if other_user.follower_count >= 49 {
                self.add_achievement(
                    &mut other_user,
                    AchievementName::Get50Followers.into(),
                    true,
                )
                .await?;
            }

            if other_user.follower_count >= 99 {
                self.add_achievement(
                    &mut other_user,
                    AchievementName::Get100Followers.into(),
                    true,
                )
                .await?;
            }

            if initiator.following_count >= 9 {
                self.add_achievement(
                    &mut initiator.clone(),
                    AchievementName::Follow10Users.into(),
                    true,
                )
                .await?;
            }
        }

        // ...
        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 user_follows VALUES ($1, $2, $3, $4)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &data.initiator.printable(),
                &data.receiver.printable()
            ]
        );

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

        // incr counts
        self.incr_user_following_count(&data.initiator)
            .await
            .unwrap();

        self.incr_user_follower_count(&data.receiver).await.unwrap();

        // return
        Ok(asked)
    }

    pub async fn delete_user_follow(
        &self,
        id: &Id,
        user: &User,
        is_deleting_user: bool,
    ) -> Result<()> {
        let follow = self.get_user_follow_by_id(id).await?;

        if (user.id != follow.initiator)
            && (user.id != follow.receiver)
            && !user.permissions.check(FinePermission::ManageFollows)
            && !is_deleting_user
        {
            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 user_follows WHERE id = $1",
            &[&id.printable()]
        );

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

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

        // decr counts (if we aren't deleting the user OR the user id isn't the deleted user id)
        if !is_deleting_user | (follow.initiator != user.id)
            && self
                .decr_user_following_count(&follow.initiator)
                .await
                .is_err()
        {
            println!("ERR_TETRATTO_DECR_FOLLOWS: could not decr initiator follow count")
        }

        if !is_deleting_user | (follow.receiver != user.id) {
            self.decr_user_follower_count(&follow.receiver)
                .await
                .unwrap();
        }

        // return
        Ok(())
    }

    pub async fn delete_user_follow_forced(&self, id: &Id, user_id: &Id) -> Result<()> {
        let follow = self.get_user_follow_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 user_follows WHERE id = $1",
            &[&id.printable()]
        );

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

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

        // decr counts
        if follow.initiator != *user_id {
            self.decr_user_following_count(&follow.initiator)
                .await
                .unwrap();
        }

        if follow.receiver != *user_id {
            self.decr_user_follower_count(&follow.receiver)
                .await
                .unwrap();
        }

        // return
        Ok(())
    }
}
