use crate::models::{db::participant::InsertableRecord as InsertableParticipant, Conversation};
use chrono::NaiveDateTime;
use diesel::prelude::*;

#[derive(Queryable, Selectable, Insertable, AsChangeset, Clone, Identifiable)]
#[diesel(table_name = crate::schema::conversations)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct Record {
    pub id: String,
    pub unread_count: i64,
    pub display_name: Option<String>,
    pub last_message_preview: Option<String>,
    pub date: NaiveDateTime,
}

impl From<Conversation> for Record {
    fn from(conversation: Conversation) -> Self {
        Self {
            id: conversation.guid,
            unread_count: conversation.unread_count as i64,
            display_name: conversation.display_name,
            last_message_preview: conversation.last_message_preview,
            date: conversation.date,
        }
    }
}

// This implementation returns the insertable data types for the conversation and participants
impl From<Conversation> for (Record, Vec<InsertableParticipant>) {
    fn from(conversation: Conversation) -> Self {
        (
            Record::from(conversation.clone()),
            conversation
                .participants
                .into_iter()
                .map(InsertableParticipant::from)
                .collect(),
        )
    }
}

impl From<Record> for Conversation {
    fn from(record: Record) -> Self {
        Self {
            guid: record.id,
            unread_count: record.unread_count as u16,
            display_name: record.display_name,
            last_message_preview: record.last_message_preview,
            date: record.date,
            participants: vec![],
        }
    }
}
