use oiseau::cache::Cache;
use crate::model::id::Id;
use crate::model::{Error, Result, auth::User, auth::UserBlock, permissions::FinePermission};
use crate::{auto_method, DataManager};

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

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

    auto_method!(get_user_block_by_id()@get_user_block_from_row -> "SELECT * FROM user_blocks WHERE id = $1" --name="user block" --returns=UserBlock --cache-key-tmpl="atto.user_block:{}");

    /// Fill a vector of user blocks with their receivers.
    pub async fn fill_user_blocks_receivers(
        &self,
        list: Vec<UserBlock>,
    ) -> Result<Vec<(UserBlock, User)>> {
        let mut out = Vec::new();

        for block in list {
            out.push(match self.get_user_by_id(&block.receiver).await {
                Ok(ua) => (block, ua),
                Err(_) => {
                    self.delete_user_block_forced(&block.id).await?;
                    continue;
                }
            });
        }

        Ok(out)
    }

    /// Get a user block by its users.
    pub async fn get_user_block_by_users(
        &self,
        initiator: &Id,
        receiver: &Id,
    ) -> Result<UserBlock> {
        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_blocks WHERE (initiator = $1 AND receiver = $2) OR (initiator = $2 AND receiver = $1)",
            &[&initiator.printable(), &receiver.printable()],
            |x| { Ok(Self::get_user_block_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

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

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

        Ok(res.unwrap())
    }

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

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

        Ok(res.unwrap())
    }

    /// Get the receiver of all user blocks for the given `initiator`.
    pub async fn get_user_blocks_receivers(&self, initiator: &Id) -> Vec<Id> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(_) => return Vec::new(),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM user_blocks WHERE initiator = $1",
            &[&initiator.printable()],
            |x| { Self::get_user_block_from_row(x) }
        );

        if res.is_err() {
            return Vec::new();
        }

        // get receivers
        let mut out: Vec<Id> = Vec::new();

        for b in res.unwrap() {
            out.push(b.receiver);
        }

        // return
        out
    }

    /// Get all user blocks created by the given `initiator`.
    pub async fn get_user_blocks_by_initiator(
        &self,
        initiator: &Id,
        batch: usize,
        page: usize,
    ) -> Vec<UserBlock> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(_) => return Vec::new(),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM user_blocks WHERE initiator = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[
                &initiator.printable(),
                &(batch as i64),
                &((page * batch) as i64)
            ],
            |x| { Self::get_user_block_from_row(x) }
        );

        if res.is_err() {
            return Vec::new();
        }

        // return
        res.unwrap()
    }

    /// Get the owner of all user blocks for the given `receiver`.
    pub async fn get_user_blocks_initiator_by_receivers(&self, receiver: &Id) -> Vec<Id> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(_) => return Vec::new(),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM user_blocks WHERE receiver = $1",
            &[&receiver.printable()],
            |x| { Self::get_user_block_from_row(x) }
        );

        if res.is_err() {
            return Vec::new();
        }

        // get owner
        let mut out: Vec<Id> = Vec::new();

        for b in res.unwrap() {
            out.push(b.initiator);
        }

        // return
        out
    }

    /// Create a new user block in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`UserBlock`] object to insert
    pub async fn create_user_block(&self, data: UserBlock) -> Result<()> {
        let initiator = self.get_user_by_id(&data.initiator).await?;
        let receiver = self.get_user_by_id(&data.receiver).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_blocks 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()));
        }

        // unfollow/remove follower
        if let Ok(f) = self
            .get_user_follow_by_initiator_receiver(&data.initiator, &data.receiver)
            .await
        {
            self.delete_user_follow(&f.id, &initiator, false).await?;
        }

        if let Ok(f) = self
            .get_user_follow_by_receiver_initiator(&data.initiator, &data.receiver)
            .await
        {
            self.delete_user_follow(&f.id, &receiver, false).await?;
        }

        // return
        Ok(())
    }

    pub async fn delete_user_block(&self, id: &crate::model::id::Id, user: User) -> Result<()> {
        let block = self.get_user_block_by_id(id).await?;

        if user.id != block.initiator {
            // only the initiator (or moderators) can delete user blocks!
            if !user.permissions.check(FinePermission::ManageFollows) {
                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_blocks WHERE id = $1",
            &[&id.printable()]
        );

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

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

        // return
        Ok(())
    }

    pub async fn delete_user_block_forced(&self, id: &crate::model::id::Id) -> Result<()> {
        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_blocks WHERE id = $1",
            &[&id.printable()]
        );

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

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

        // return
        Ok(())
    }
}
