use chrono::{DateTime, Utc};
use diesel::{
    dsl::{auto_type, AsSelect},
    pg::Pg,
    prelude::*,
};
use uuid::Uuid;

use crate::{channels::Channel, schema::messages};

/// A "/say" message queued for sending
#[derive(Associations, Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = messages)]
#[diesel(belongs_to(Channel))]
pub struct Message {
    pub id: Uuid,
    pub project_id: Uuid,
    pub channel_id: Uuid,
    pub created_at: DateTime<Utc>,
    pub sent_at: Option<DateTime<Utc>>,
    pub message: String,
}

impl Message {
    #[auto_type(no_type_alias)]
    pub fn all() -> _ {
        let select: AsSelect<Message, Pg> = Message::as_select();
        messages::table.select(select)
    }

    #[auto_type(no_type_alias)]
    pub fn with_channel<'a>(channel_id: &'a Uuid) -> _ {
        messages::channel_id.eq(channel_id)
    }

    #[auto_type(no_type_alias)]
    pub fn is_not_sent() -> _ {
        messages::sent_at.is_null()
    }
}
