use oiseau::cache::Cache;
use crate::model::id::Id;
use crate::model::socket::{CrudMessageType, PacketType, SocketMessage, SocketMethod};
use crate::model::{Error, Result, auth::Notification, auth::User, permissions::FinePermission};
use crate::{auto_method, DataManager};

use oiseau::{PostgresRow, cache::redis::Commands};
use oiseau::{execute, get, query_rows, params};

impl DataManager {
    /// Get a [`Notification`] from an SQL row.
    pub(crate) fn get_notification_from_row(x: &PostgresRow) -> Notification {
        Notification {
            id: crate::model::id::Id::deserialize(&get!(x->0(String))),
            created: get!(x->1(i64)) as u128,
            title: get!(x->2(String)),
            content: get!(x->3(String)),
            owner: crate::model::id::Id::deserialize(&get!(x->4(String))),
            read: get!(x->5(i32)) as i8 == 1,
            tag: get!(x->6(String)),
        }
    }

    auto_method!(get_notification_by_id()@get_notification_from_row -> "SELECT * FROM notifications WHERE id = $1" --name="notification" --returns=Notification --cache-key-tmpl="atto.notification:{}");

    /// Get all notifications by `owner`.
    pub async fn get_notifications_by_owner(&self, owner: &Id) -> Result<Vec<Notification>> {
        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 notifications WHERE owner = $1 ORDER BY created DESC",
            &[&owner.printable()],
            |x| { Self::get_notification_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all notifications by `owner` (paginated).
    pub async fn get_notifications_by_owner_paginated(
        &self,
        owner: &Id,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Notification>> {
        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 notifications WHERE owner = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[
                &owner.printable(),
                &(batch as i64),
                &((page * batch) as i64)
            ],
            |x| { Self::get_notification_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all notifications by `tag`.
    pub async fn get_notifications_by_tag(&self, tag: &str) -> Result<Vec<Notification>> {
        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 notifications WHERE tag = $1 ORDER BY created DESC",
            &[&tag],
            |x| { Self::get_notification_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Create a new notification in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Notification`] object to insert
    pub async fn create_notification(&self, data: Notification) -> 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 notifications VALUES ($1, $2, $3, $4, $5, $6, $7)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &data.title,
                &data.content,
                &data.owner.printable(),
                &{ if data.read { 1 } else { 0 } },
                &data.tag
            ]
        );

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

        // incr notification count
        self.incr_user_notifications(&data.owner).await?;

        // post event
        let mut con = self.0.1.get_con().await;

        if let Err(e) = con.publish::<String, String, ()>(
            format!("{}/notifs", data.owner),
            serde_json::to_string(&SocketMessage {
                method: SocketMethod::Packet(PacketType::Crud(CrudMessageType::Create)),
                data: serde_json::to_string(&data).unwrap(),
            })
            .unwrap(),
        ) {
            return Err(Error::MiscError(e.to_string()));
        }

        // return
        Ok(())
    }

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

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

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

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

        // decr notification count
        if !notification.read {
            self.decr_user_notifications(&notification.owner)
                .await
                .unwrap();
        }

        // post event
        let mut con = self.0.1.get_con().await;

        if let Err(e) = con.publish::<String, String, ()>(
            format!("{}/notifs", notification.owner),
            serde_json::to_string(&SocketMessage {
                method: SocketMethod::Packet(PacketType::Crud(CrudMessageType::Delete)),
                data: notification.id.to_string(),
            })
            .unwrap(),
        ) {
            return Err(Error::MiscError(e.to_string()));
        }

        // return
        Ok(())
    }

    pub async fn delete_all_notifications(&self, user: &User) -> Result<()> {
        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 notifications WHERE owner = $1",
            &[&user.id.printable()]
        );

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

        self.update_user_notification_count(&user.id, 0).await?;
        Ok(())
    }

    pub async fn delete_all_notifications_by_tag(&self, user: &User, tag: &str) -> Result<()> {
        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 notifications WHERE owner = $1 AND tag = $2",
            params![&user.id.printable(), tag]
        );

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

        Ok(())
    }

    pub async fn update_notification_read(
        &self,
        id: &crate::model::id::Id,
        new_read: bool,
        user: &User,
    ) -> Result<()> {
        let y = self.get_notification_by_id(id).await?;

        if y.owner != user.id && !user.permissions.check(FinePermission::ManageNotifications) {
            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,
            "UPDATE notifications SET read = $1 WHERE id = $2",
            params![&{ if new_read { 1 } else { 0 } }, &id.printable()]
        );

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

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

        if (y.read) && (!new_read) {
            self.incr_user_notifications(&user.id).await?;
        } else if (!y.read) && (new_read) {
            self.decr_user_notifications(&user.id).await?;
        }

        Ok(())
    }

    pub async fn update_all_notifications_read(&self, user: &User, read: bool) -> Result<()> {
        let notifications = self.get_notifications_by_owner(&user.id).await?;

        let mut changed_count: i32 = 0;
        for notification in notifications {
            if notification.read == read {
                // no need to update this
                continue;
            }

            changed_count += 1;

            self.0
                .1
                .remove(format!("atto.notification:{}", notification.id))
                .await;
        }

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

        let res = execute!(
            &conn,
            "UPDATE notifications SET read = $1 WHERE owner = $2",
            params![&{ if read { 1 } else { 0 } }, &user.id.printable()]
        );

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

        // use changed_count to update user counts
        if !read {
            // we don't need to update when marking things as read since that should just be 0
            self.update_user_notification_count(&user.id, changed_count)
                .await?;
        } else {
            self.update_user_notification_count(&user.id, 0).await?;
        }

        // ...
        Ok(())
    }
}
