package repositories

import (
	"gorm.io/gorm"
	"messageService/internal/app/models"
)

type MessageRepository interface {
	GetAllMessages() ([]models.Message, error)
	GetMessageByID(id uint) (*models.Message, error)
	GetMessagesByStreamID(streamID uint) ([]models.Message, error)
	CreateMessage(message *models.Message) error
	UpdateMessage(message *models.Message) error
	DeleteMessage(id uint) error
}

type messageRepository struct {
	db *gorm.DB
}

func NewMessageRepository(db *gorm.DB) MessageRepository {
	return &messageRepository{db: db}
}

func (r *messageRepository) GetAllMessages() ([]models.Message, error) {
	var messages []models.Message
	if err := r.db.Find(&messages).Error; err != nil {
		return nil, err
	}
	return messages, nil
}

func (r *messageRepository) GetMessageByID(id uint) (*models.Message, error) {
	var message models.Message
	if err := r.db.First(&message, id).Error; err != nil {
		return nil, err
	}
	return &message, nil
}

func (r *messageRepository) GetMessagesByStreamID(streamID uint) ([]models.Message, error) {
	var messages []models.Message
	if err := r.db.Where("stream_id = ?", streamID).Find(&messages).Error; err != nil {
		return nil, err
	}
	return messages, nil
}

func (r *messageRepository) CreateMessage(message *models.Message) error {
	return r.db.Create(message).Error
}

func (r *messageRepository) UpdateMessage(message *models.Message) error {
	var existingMessage models.Message
	if err := r.db.First(&existingMessage, message.ID).Error; err != nil {
		return err
	}

	return r.db.Model(&existingMessage).Updates(message).Error
}

func (r *messageRepository) DeleteMessage(id uint) error {
	return r.db.Delete(&models.Message{}, id).Error
}
