use crate::models::Participant;
use crate::schema::conversation_participants;
use diesel::prelude::*;

#[derive(Queryable, Selectable, AsChangeset, Identifiable)]
#[diesel(table_name = crate::schema::participants)]
#[diesel(primary_key(handle))]
pub struct Record {
    pub handle: String,
    pub is_me: bool,
    pub contact_id: Option<String>,
}

#[derive(Insertable)]
#[diesel(table_name = crate::schema::participants)]
pub struct InsertableRecord {
    pub handle: String,
    pub is_me: bool,
    pub contact_id: Option<String>,
}

impl From<Participant> for InsertableRecord {
    fn from(participant: Participant) -> Self {
        match participant {
            Participant::Me => InsertableRecord {
                handle: "me".to_string(),
                is_me: true,
                contact_id: None,
            },
            Participant::Remote {
                handle, contact_id, ..
            } => InsertableRecord {
                handle,
                is_me: false,
                contact_id,
            },
        }
    }
}

#[derive(Identifiable, Selectable, Queryable, Associations, Debug)]
#[diesel(belongs_to(super::conversation::Record, foreign_key = conversation_id))]
#[diesel(belongs_to(Record, foreign_key = participant_handle))]
#[diesel(table_name = conversation_participants)]
#[diesel(primary_key(conversation_id, participant_handle))]
pub struct ConversationParticipant {
    pub conversation_id: String,
    pub participant_handle: String,
}

impl From<Record> for Participant {
    fn from(record: Record) -> Self {
        if record.is_me {
            Participant::Me
        } else {
            Participant::Remote {
                handle: record.handle.clone(),
                contact_id: record.contact_id,
            }
        }
    }
}

impl From<Participant> for Record {
    fn from(participant: Participant) -> Self {
        match participant {
            Participant::Me => Record {
                handle: "me".to_string(),
                is_me: true,
                contact_id: None,
            },
            Participant::Remote {
                handle, contact_id, ..
            } => Record {
                handle,
                is_me: false,
                contact_id,
            },
        }
    }
}
