use crate::models::{Message, Participant};
use chrono::NaiveDateTime;
use diesel::prelude::*;

#[derive(Queryable, Selectable, Insertable, AsChangeset, Clone, Identifiable, Debug)]
#[diesel(table_name = crate::schema::messages)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct Record {
    pub id: String,
    pub sender_participant_handle: Option<String>,
    pub text: String,
    pub date: NaiveDateTime,
    pub file_transfer_guids: Option<String>, // JSON array
    pub attachment_metadata: Option<String>, // JSON string
}

impl From<Message> for Record {
    fn from(message: Message) -> Self {
        let file_transfer_guids = if message.file_transfer_guids.is_empty() {
            None
        } else {
            Some(serde_json::to_string(&message.file_transfer_guids).unwrap_or_default())
        };

        let attachment_metadata = message
            .attachment_metadata
            .map(|metadata| serde_json::to_string(&metadata).unwrap_or_default());

        Self {
            id: message.id,
            sender_participant_handle: match message.sender {
                Participant::Me => None,
                Participant::Remote { handle, .. } => Some(handle),
            },
            text: message.text,
            date: message.date,
            file_transfer_guids,
            attachment_metadata,
        }
    }
}

impl From<Record> for Message {
    fn from(record: Record) -> Self {
        let file_transfer_guids = record
            .file_transfer_guids
            .and_then(|json| serde_json::from_str(&json).ok())
            .unwrap_or_default();

        let attachment_metadata = record
            .attachment_metadata
            .and_then(|json| serde_json::from_str(&json).ok());

        let message_sender = match record.sender_participant_handle {
            Some(handle) => Participant::Remote {
                handle,
                contact_id: None,
            },
            None => Participant::Me,
        };
        Self {
            id: record.id,
            sender: message_sender,
            text: record.text,
            date: record.date,
            file_transfer_guids,
            attachment_metadata,
        }
    }
}
