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

use oiseau::PostgresRow;

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

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

    auto_method!(get_report_by_id()@get_report_from_row -> "SELECT * FROM reports WHERE id = $1" --name="report" --returns=Report --cache-key-tmpl="atto.reports:{}");

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

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

        Ok(res.unwrap())
    }

    /// Create a new report in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Report`] object to insert
    pub async fn create_report(&self, data: Report) -> 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 reports VALUES ($1, $2, $3, $4, $5, $6)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &data.owner.printable(),
                &data.content.as_str(),
                &data.asset.printable(),
                &serde_json::to_string(&data.asset_type).unwrap().as_str(),
            ]
        );

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

        // return
        Ok(())
    }

    pub async fn delete_report(&self, id: &crate::model::id::Id, user: User) -> Result<()> {
        self.get_report_by_id(id).await?;

        if !user.permissions.check(FinePermission::ManageReports) {
            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 reports WHERE id = $1",
            &[&id.printable()]
        );

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

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

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

        // return
        Ok(())
    }
}
