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

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "room_message_reaction")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: Uuid,
    pub room: RoomId,
    pub message: MessageId,
    pub user: UserId,
    pub emoji: String,
    pub created_at: DateTimeUtc,
}

#[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_message::Entity",
        from = "Column::Message",
        to = "super::room_message::Column::Id"
    )]
    Message,
    #[sea_orm(
        belongs_to = "super::room_member::Entity",
        from = "(Column::Room, Column::User)",
        to = "(super::room_member::Column::Room, super::room_member::Column::User)"
    )]
    Member,
}

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

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

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

impl ActiveModelBehavior for ActiveModel {}

/// Aggregated reaction counts per message for API responses
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageReactionSummary {
    pub message_id: UserId,
    /// emoji -> { count, reacted_by_current_user }
    pub reactions: Vec<ReactionGroup>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReactionGroup {
    pub emoji: String,
    pub count: i64,
    pub reacted_by_me: bool,
    /// Sample of users who reacted (first 3)
    pub users: Vec<UserId>,
}
