package repository

import (
	"context"
	"errors"
	"time"

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

type SystemSettingRepository interface {
	Get(ctx context.Context, key string) (*entity.SystemSetting, error)
	Set(ctx context.Context, key, value string) error
	List(ctx context.Context) ([]entity.SystemSetting, error)
	GetAllowNegativePakanOVK(ctx context.Context) (bool, error)
}

type systemSettingRepositoryImpl struct {
	db *gorm.DB
}

func NewSystemSettingRepository(db *gorm.DB) SystemSettingRepository {
	return &systemSettingRepositoryImpl{db: db}
}

func (r *systemSettingRepositoryImpl) Get(ctx context.Context, key string) (*entity.SystemSetting, error) {
	var setting entity.SystemSetting
	if err := r.db.WithContext(ctx).Where("key = ?", key).First(&setting).Error; err != nil {
		return nil, err
	}
	return &setting, nil
}

func (r *systemSettingRepositoryImpl) Set(ctx context.Context, key, value string) error {
	return r.db.WithContext(ctx).
		Model(&entity.SystemSetting{}).
		Where("key = ?", key).
		Updates(map[string]interface{}{
			"value":      value,
			"updated_at": time.Now(),
		}).Error
}

func (r *systemSettingRepositoryImpl) List(ctx context.Context) ([]entity.SystemSetting, error) {
	var settings []entity.SystemSetting
	if err := r.db.WithContext(ctx).Order("key ASC").Find(&settings).Error; err != nil {
		return nil, err
	}
	return settings, nil
}

func (r *systemSettingRepositoryImpl) GetAllowNegativePakanOVK(ctx context.Context) (bool, error) {
	setting, err := r.Get(ctx, entity.SystemSettingKeyAllowNegativePakanOVK)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false, nil
		}
		return false, err
	}
	return setting.Value == "true", nil
}
