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

impl DataManager {
    /// Get an [`IpBlock`] from an SQL row.
    pub(crate) fn get_ip_block_from_row(x: &PostgresRow) -> IpBlock {
        IpBlock {
            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: get!(x->3(String)),
        }
    }

    auto_method!(get_ip_block_by_id()@get_ip_block_from_row -> "SELECT * FROM ip_blocks WHERE id = $1" --name="ip block" --returns=IpBlock --cache-key-tmpl="atto.ip_block:{}");

    /// Get a ip block by `initiator` and `receiver` (in that order).
    pub async fn get_ip_block_by_initiator_receiver(
        &self,
        initiator: &Id,
        receiver: &RemoteAddr,
    ) -> Result<IpBlock> {
        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 ip_blocks WHERE initiator = $1 AND receiver LIKE $2",
            params![
                &initiator.printable(),
                &format!("{}%", receiver.prefix(None))
            ],
            |x| { Ok(Self::get_ip_block_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Get a ip block by `receiver` and `initiator` (in that order).
    pub async fn get_ip_block_by_receiver_initiator(
        &self,
        receiver: &str,
        initiator: &Id,
    ) -> Result<IpBlock> {
        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 ip_blocks WHERE receiver = $1 AND initiator = $2",
            params![&receiver, &initiator.printable()],
            |x| { Ok(Self::get_ip_block_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all ip blocks by `initiator`.
    pub async fn get_ip_blocks_by_initiator(&self, initiator: &Id) -> Result<Vec<IpBlock>> {
        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 ip_blocks WHERE initiator = $1",
            params![&initiator.printable()],
            |x| { Self::get_ip_block_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Create a new ip block in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`IpBlock`] object to insert
    pub async fn create_ip_block(&self, data: IpBlock) -> Result<()> {
        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 ip_blocks VALUES ($1, $2, $3, $4)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &data.initiator.printable(),
                &data.receiver
            ]
        );

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

        // return
        Ok(())
    }

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

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

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

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

        // return
        Ok(())
    }
}
