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

use oiseau::PostgresRow;

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

impl DataManager {
    /// Get a [`Poll`] from an SQL row.
    pub(crate) fn get_poll_from_row(x: &PostgresRow) -> Poll {
        Poll {
            id: Id::deserialize(&get!(x->0(String))),
            owner: Id::deserialize(&get!(x->1(String))),
            created: get!(x->2(i64)) as u128,
            expires: get!(x->3(i32)) as u128,
            option_a: get!(x->4(String)),
            option_b: get!(x->5(String)),
            option_c: get!(x->6(String)),
            option_d: get!(x->7(String)),
            votes_a: get!(x->8(i32)) as usize,
            votes_b: get!(x->9(i32)) as usize,
            votes_c: get!(x->10(i32)) as usize,
            votes_d: get!(x->11(i32)) as usize,
        }
    }

    auto_method!(get_poll_by_id()@get_poll_from_row -> "SELECT * FROM polls WHERE id = $1" --name="poll" --returns=Poll --cache-key-tmpl="atto.poll:{}");

    /// Get all polls by their owner.
    ///
    /// # Arguments
    /// * `owner` - the ID of the owner of the polls
    pub async fn get_polls_by_owner_all(&self, owner: crate::model::id::Id) -> Result<Vec<Poll>> {
        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 polls WHERE owner = $1 ORDER BY created DESC",
            &[&owner.printable()],
            |x| { Self::get_poll_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Create a new poll in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Poll`] object to insert
    pub async fn create_poll(&self, data: Poll) -> Result<Id> {
        // check values
        if data.option_a.len() < 2 {
            return Err(Error::DataTooShort("option A".to_string()));
        } else if data.option_a.len() > 128 {
            return Err(Error::DataTooLong("option A".to_string()));
        }

        if data.option_b.len() < 2 {
            return Err(Error::DataTooShort("option B".to_string()));
        } else if data.option_b.len() > 128 {
            return Err(Error::DataTooLong("option B".to_string()));
        }

        if data.option_c.len() > 128 {
            return Err(Error::DataTooLong("option C".to_string()));
        }

        if data.option_d.len() > 128 {
            return Err(Error::DataTooLong("option D".to_string()));
        }

        // ...
        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 polls VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
            params![
                &data.id.printable(),
                &data.owner.printable(),
                &(data.created as i64),
                &(data.expires as i32),
                &data.option_a,
                &data.option_b,
                &data.option_c,
                &data.option_d,
                &(data.votes_a as i32),
                &(data.votes_b as i32),
                &(data.votes_c as i32),
                &(data.votes_d as i32),
            ]
        );

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

        Ok(data.id)
    }

    pub async fn delete_poll(&self, id: &Id, user: &User) -> Result<()> {
        let y = self.get_poll_by_id(id).await?;

        if user.id != y.owner {
            if !user.permissions.check(FinePermission::ManagePosts) {
                return Err(Error::NotAllowed);
            } else {
                self.create_audit_log_entry(AuditLogEntry::new(
                    user.id.to_owned(),
                    format!("invoked `delete_poll` with x value `{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 polls WHERE id = $1", &[&id.printable()]);

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

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

        // remove votes
        let res = execute!(
            &conn,
            "DELETE FROM pollvotes WHERE poll_id = $1",
            &[&id.printable()]
        );

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

        // ...
        Ok(())
    }

    pub async fn cache_clear_poll(&self, poll: &Poll) {
        self.0.1.remove(format!("atto.poll:{}", poll.id)).await;
    }

    auto_method!(incr_votes_a_count()@get_poll_by_id -> "UPDATE polls SET votes_a = votes_a + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
    auto_method!(decr_votes_a_count()@get_poll_by_id -> "UPDATE polls SET votes_a = votes_a - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_a);

    auto_method!(incr_votes_b_count()@get_poll_by_id -> "UPDATE polls SET votes_b = votes_b + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
    auto_method!(decr_votes_b_count()@get_poll_by_id -> "UPDATE polls SET votes_b = votes_b - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_b);

    auto_method!(incr_votes_c_count()@get_poll_by_id -> "UPDATE polls SET votes_c = votes_d + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
    auto_method!(decr_votes_c_count()@get_poll_by_id -> "UPDATE polls SET votes_c = votes_d - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_c);

    auto_method!(incr_votes_d_count()@get_poll_by_id -> "UPDATE polls SET votes_d = votes_d + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
    auto_method!(decr_votes_d_count()@get_poll_by_id -> "UPDATE polls SET votes_d = votes_d - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_d);
}
