use crate::{DateTimeUtc, MessageId, RoomId, RoomThreadId, Seq, UserId};
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

use super::{MessageContentType, MessageSenderType};

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "room_message")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: MessageId,
    pub seq: Seq,
    pub room: RoomId,
    pub sender_type: MessageSenderType,
    pub sender_id: Option<UserId>,
    pub thread: Option<RoomThreadId>,
    pub in_reply_to: Option<MessageId>,
    pub content: String,
    pub content_type: MessageContentType,
    pub edited_at: Option<DateTimeUtc>,
    pub send_at: DateTimeUtc,
    pub revoked: Option<DateTimeUtc>,
    pub revoked_by: Option<UserId>,
    #[sea_orm(ignore)]
    pub content_tsv: Option<String>,
}

impl Model {
    #[deprecated(since = "0.1.0", note = "sender_type is now an enum")]
    pub fn sender_type_enum(&self) -> Result<MessageSenderType, &'static str> {
        Ok(self.sender_type.clone())
    }

    #[deprecated(since = "0.1.0", note = "content_type is now an enum")]
    pub fn content_type_enum(&self) -> Result<MessageContentType, &'static str> {
        Ok(self.content_type.clone())
    }
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
    #[sea_orm(
        belongs_to = "super::room::Entity",
        from = "Column::Room",
        to = "super::room::Column::Id"
    )]
    Room,
    #[sea_orm(
        belongs_to = "super::room_thread::Entity",
        from = "Column::Thread",
        to = "super::room_thread::Column::Id"
    )]
    Thread,
}

impl Related<super::room::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::Room.def()
    }
}

impl Related<super::room_thread::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::Thread.def()
    }
}

impl ActiveModelBehavior for ActiveModel {}
