package model

import (
	"encoding/json"
	"time"

	"gorm.io/gorm"
)

// Message represents a single message within a conversation.
// Reference: Chatwoot Message model + P2B M3 spec
type Message struct {
	ID                  uint           `gorm:"primaryKey" json:"id"`
	AccountID           uint           `gorm:"not null;index" json:"account_id"`
	InboxID             uint           `gorm:"not null;index" json:"inbox_id"`
	ConversationID      uint           `gorm:"not null;index" json:"conversation_id"`
	UserID              *uint          `gorm:"index" json:"user_id,omitempty"`
	Content             string         `gorm:"type:text" json:"content"`
	ContentType         string         `gorm:"size:50;not null;default:'text'" json:"content_type"` // text/input_text/input_email/image/audio/video/file/location/emoji/extended/quote/contact
	MessageType         string         `gorm:"size:50;not null;index" json:"message_type"` // incoming/outgoing/activity/template/private
	SenderType          string         `gorm:"size:50" json:"sender_type"` // Contact/User/AgentBot
	SenderID            uint           `gorm:"index" json:"sender_id"`
	Status              string         `gorm:"size:50;default:'sent'" json:"status"` // sent/delivered/read/failed
	SourceID            string         `gorm:"size:255;index" json:"source_id"`
	Private             bool           `gorm:"default:false" json:"private"`
	External            bool           `gorm:"default:false" json:"external"`
	AdditionalAttributes json.RawMessage `gorm:"type:jsonb" json:"additional_attributes"`
	CustomAttributes    json.RawMessage `gorm:"type:jsonb" json:"custom_attributes"`
	InReplyTo           *uint          `gorm:"index" json:"in_reply_to,omitempty"`
	ParentID            *uint          `gorm:"index" json:"parent_id,omitempty"`
	DeletedAt           gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
	CreatedAt           time.Time      `gorm:"autoCreateTime;index" json:"created_at"`
	UpdatedAt           time.Time      `gorm:"autoUpdateTime" json:"updated_at"`

	Conversation Conversation `gorm:"foreignKey:ConversationID" json:"conversation,omitempty"`
	Inbox        Inbox        `gorm:"foreignKey:InboxID" json:"inbox,omitempty"`
	Sender       User         `gorm:"foreignKey:UserID" json:"sender,omitempty"`
	Attachments  []Attachment `gorm:"foreignKey:MessageID" json:"attachments,omitempty"`
	Reactions    []MessageReaction `gorm:"foreignKey:MessageID" json:"reactions,omitempty"`
}

func (Message) TableName() string { return "messages" }