package store

import (
	"encoding/json"
	"errors"
	"time"

	"github.com/wormhole/wormhole/internal/config"
	"gorm.io/gorm"
)

const systemSettingsID = 1

type SystemSettings struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	Payload   string    `gorm:"type:text;not null" json:"-"`
	UpdatedAt time.Time `json:"updated_at"`
}

func (s *Store) ensureSystemSettings() error {
	var row SystemSettings
	err := s.db.First(&row, systemSettingsID).Error
	if err == nil {
		return nil
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}
	cfg := config.Default()
	payload, err := json.Marshal(cfg)
	if err != nil {
		return err
	}
	return s.db.Create(&SystemSettings{
		ID:      systemSettingsID,
		Payload: string(payload),
	}).Error
}

func (s *Store) LoadConfig() (*config.Config, error) {
	if err := s.ensureSystemSettings(); err != nil {
		return nil, err
	}
	var row SystemSettings
	if err := s.db.First(&row, systemSettingsID).Error; err != nil {
		return nil, err
	}
	cfg := config.Default()
	if err := json.Unmarshal([]byte(row.Payload), cfg); err != nil {
		return nil, err
	}
	cfg.Database.Path = config.DefaultDBPath
	cfg.Normalize()
	return cfg, nil
}

func (s *Store) SaveConfig(cfg *config.Config) error {
	if err := s.ensureSystemSettings(); err != nil {
		return err
	}
	cfg.Database.Path = config.DefaultDBPath
	cfg.Normalize()
	payload, err := json.Marshal(cfg)
	if err != nil {
		return err
	}
	return s.db.Model(&SystemSettings{}).Where("id = ?", systemSettingsID).Updates(map[string]interface{}{
		"payload":    string(payload),
		"updated_at": time.Now(),
	}).Error
}
