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

use oiseau::PostgresRow;

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

impl DataManager {
    /// Get a [`PollVote`] from an SQL row.
    pub(crate) fn get_poll_vote_from_row(x: &PostgresRow) -> PollVote {
        PollVote {
            id: Id::deserialize(&get!(x->0(String))),
            owner: Id::deserialize(&get!(x->1(String))),
            created: get!(x->2(i64)) as u128,
            poll_id: Id::deserialize(&get!(x->3(String))),
            vote: (get!(x->4(i32)) as u8).into(),
        }
    }

    auto_method!(get_poll_vote_by_id()@get_poll_vote_from_row -> "SELECT * FROM poll_votes WHERE id = $1" --name="poll vote" --returns=PollVote --cache-key-tmpl="atto.poll_vote:{}");

    pub async fn get_poll_vote_by_owner_poll(&self, id: &Id, poll_id: &Id) -> Result<PollVote> {
        if let Some(cached) = self
            .0
            .1
            .get(format!("atto.poll_vote:{}:{}", id, poll_id))
            .await
        {
            return Ok(serde_json::from_str(&cached).unwrap());
        }

        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 poll_votes WHERE owner = $1 AND poll_id = $2",
            &[&id.printable(), &poll_id.printable()],
            |x| { Ok(Self::get_poll_vote_from_row(x)) }
        );

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

        let x = res.unwrap();
        self.0
            .1
            .set(
                format!("atto.poll_vote:{}:{}", id, poll_id),
                serde_json::to_string(&x).unwrap(),
            )
            .await;

        Ok(x)
    }

    /// Create a new poll vote in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`PollVote`] object to insert
    pub async fn create_poll_vote(&self, data: PollVote) -> Result<Id> {
        // get poll and check permission
        let poll = self.get_poll_by_id(&data.poll_id).await?;

        let now = unix_epoch_timestamp();
        let diff = now - poll.created;

        if diff > poll.expires {
            return Err(Error::MiscError("Poll is closed".to_string()));
        };

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let vote_u8: u8 = data.vote.into();
        let res = execute!(
            &conn,
            "INSERT INTO poll_votes VALUES ($1, $2, $3, $4, $5)",
            params![
                &data.id.printable(),
                &data.owner.printable(),
                &(data.created as i64),
                &data.poll_id.printable(),
                &(vote_u8 as i32),
            ]
        );

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

        // update poll
        match data.vote {
            PollOption::A => {
                self.incr_votes_a_count(&poll.id).await?;
            }
            PollOption::B => {
                self.incr_votes_b_count(&poll.id).await?;
            }
            PollOption::C => {
                self.incr_votes_c_count(&poll.id).await?;
            }
            PollOption::D => {
                self.incr_votes_d_count(&poll.id).await?;
            }
        };

        // ...
        Ok(data.id)
    }

    pub async fn delete_poll_vote(&self, id: &Id, user: User) -> Result<()> {
        let y = self.get_poll_vote_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,
                    format!("invoked `delete_poll_vote` 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 poll_votes WHERE id = $1",
            &[&id.printable()]
        );

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

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

        Ok(())
    }
}
