package repositories

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

type StreamRepository interface {
	GetAllStreams() ([]models.Stream, error)
	GetStreamByID(id uint) (*models.Stream, error)
	CreateStream(stream *models.Stream) error
	UpdateStream(stream *models.Stream) error
	DeleteStream(id uint) error
}

type streamRepository struct {
	db *gorm.DB
}

func NewStreamRepository(db *gorm.DB) StreamRepository {
	return &streamRepository{db: db}
}

func (r *streamRepository) GetAllStreams() ([]models.Stream, error) {
	var streams []models.Stream
	if err := r.db.Find(&streams).Error; err != nil {
		return nil, err
	}
	return streams, nil
}

func (r *streamRepository) GetStreamByID(id uint) (*models.Stream, error) {
	var stream models.Stream
	if err := r.db.First(&stream, id).Error; err != nil {
		return nil, err
	}
	return &stream, nil
}

func (r *streamRepository) CreateStream(stream *models.Stream) error {
	return r.db.Create(stream).Error
}

func (r *streamRepository) UpdateStream(stream *models.Stream) error {
	var existingStream models.Stream
	if err := r.db.First(&existingStream, stream.ID).Error; err != nil {
		return err
	}

	return r.db.Model(&existingStream).Updates(stream).Error
}

func (r *streamRepository) DeleteStream(id uint) error {
	return r.db.Delete(&models.Stream{}, id).Error
}
