package repository

import (
	"context"
	"fmt"

	"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	"gorm.io/gorm"
)

type MarketingRepository interface {
	repository.BaseRepository[entity.Marketing]
	IdExists(ctx context.Context, id uint) (bool, error)
	GetNextSequence(ctx context.Context) (uint, error)
	NextSoNumber(ctx context.Context, tx *gorm.DB) (string, error)
}

type MarketingRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.Marketing]
}

func NewMarketingRepository(db *gorm.DB) MarketingRepository {
	return &MarketingRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.Marketing](db),
	}
}

func (r *MarketingRepositoryImpl) IdExists(ctx context.Context, id uint) (bool, error) {
	return repository.Exists[entity.Marketing](ctx, r.DB(), id)
}

func (r *MarketingRepositoryImpl) GetNextSequence(ctx context.Context) (uint, error) {
	var maxID uint
	if err := r.DB().WithContext(ctx).Model(&entity.Marketing{}).Select("COALESCE(MAX(id), 0)").Scan(&maxID).Error; err != nil {
		return 0, err
	}
	return maxID + 1, nil
}

func (r *MarketingRepositoryImpl) NextSoNumber(ctx context.Context, tx *gorm.DB) (string, error) {
	db := tx
	if db == nil {
		db = r.DB()
	}

	var soNumber string
	err := db.WithContext(ctx).
		Raw("SELECT generate_so_number()").
		Scan(&soNumber).Error

	if err != nil {
		return "", fmt.Errorf("failed to generate SO number: %w", err)
	}

	return soNumber, nil
}
