use oiseau::cache::Cache;
use crate::model::addr::RemoteAddr;
use crate::model::moderation::AuditLogEntry;
use crate::model::{Error, Result, auth::IpBan, auth::User, permissions::FinePermission, id::Id};
use crate::{auto_method, DataManager};

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

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

    auto_method!(get_ip_ban_by_ip(&str)@get_ip_ban_from_row -> "SELECT * FROM ip_bans WHERE ip = $1" --name="ip ban" --returns=IpBan --cache-key-tmpl="atto.ip_ban:{}");

    /// Get an IP ban as a [`RemoteAddr`].
    ///
    /// # Arguments
    /// * `prefix`
    pub async fn get_ip_ban_by_addr(&self, addr: &RemoteAddr) -> Result<IpBan> {
        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_bans WHERE ip = $1",
            &[&addr.prefix(None)],
            |x| { Ok(Self::get_ip_ban_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all IP bans (paginated).
    ///
    /// # Arguments
    /// * `batch` - the limit of items in each page
    /// * `page` - the page number
    pub async fn get_ip_bans(&self, batch: usize, page: usize) -> Result<Vec<IpBan>> {
        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_bans ORDER BY created DESC LIMIT $1 OFFSET $2",
            &[&(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_ip_ban_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Create a new IP ban in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`IpBan`] object to insert
    pub async fn create_ip_ban(&self, data: IpBan) -> Result<()> {
        let user = self.get_user_by_id(&data.moderator).await?;

        // ONLY moderators can create ip bans
        if !user.permissions.check(FinePermission::ManageBans) {
            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,
            "INSERT INTO ip_bans VALUES ($1, $2, $3, $4)",
            params![
                &data.ip.as_str(),
                &(data.created as i64),
                &data.reason.as_str(),
                &data.moderator.printable()
            ]
        );

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

        // create audit log entry
        self.create_audit_log_entry(AuditLogEntry::new(
            user.id,
            format!("invoked `create_ipban` with x value `{}`", data.ip),
        ))
        .await?;

        // return
        Ok(())
    }

    pub async fn delete_ip_ban(&self, ip: &str, user: User) -> Result<()> {
        // ONLY moderators can manage ip bans
        if !user.permissions.check(FinePermission::ManageBans) {
            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_bans WHERE ip = $1", &[&ip]);

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

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

        // create audit log entry
        self.create_audit_log_entry(AuditLogEntry::new(
            user.id,
            format!("invoked `delete_ipban` with x value `{ip}`"),
        ))
        .await?;

        // return
        Ok(())
    }
}
