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

use crate::{projects::Project, schema::messages};

#[derive(Associations, Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = messages)]
#[diesel(belongs_to(Project))]
pub struct Message {
    pub id: Uuid,
    pub project_id: Uuid,
    pub created_at: 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_project(project_id: Uuid) -> _ {
        messages::project_id.eq(project_id)
    }

    #[auto_type(no_type_alias)]
    pub fn values_now(project_id: Uuid, message: String) -> _ {
        let id: Uuid = Uuid::now_v7();
        (
            messages::id.eq(id),
            messages::project_id.eq(project_id),
            messages::message.eq(message),
        )
    }
}
