package service

import (
	"context"

	"github.com/gofiber/fiber/v2"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	repository "gitlab.com/mbugroup/lti-api.git/internal/modules/system-settings/repositories"
)

type SystemSettingService interface {
	GetAll(ctx context.Context) ([]entity.SystemSetting, error)
	GetAllowNegativePakanOVK(ctx context.Context) (bool, error)
	SetAllowNegativePakanOVK(ctx context.Context, allow bool) error
}

type systemSettingService struct {
	Repository repository.SystemSettingRepository
}

func NewSystemSettingService(repo repository.SystemSettingRepository) SystemSettingService {
	return &systemSettingService{Repository: repo}
}

func (s *systemSettingService) GetAll(ctx context.Context) ([]entity.SystemSetting, error) {
	settings, err := s.Repository.List(ctx)
	if err != nil {
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Gagal mengambil system settings")
	}
	return settings, nil
}

func (s *systemSettingService) GetAllowNegativePakanOVK(ctx context.Context) (bool, error) {
	return s.Repository.GetAllowNegativePakanOVK(ctx)
}

func (s *systemSettingService) SetAllowNegativePakanOVK(ctx context.Context, allow bool) error {
	value := "false"
	if allow {
		value = "true"
	}
	if err := s.Repository.Set(ctx, entity.SystemSettingKeyAllowNegativePakanOVK, value); err != nil {
		return fiber.NewError(fiber.StatusInternalServerError, "Gagal mengubah setting allow_negative_pakan_ovk")
	}
	return nil
}
