package service

import (
	"encoding/json"
	"os"
	"path/filepath"

	"sproutworkcollect-backend/internal/config"
	"sproutworkcollect-backend/internal/model"
)

var defaultSettings = model.Settings{
	SiteName:       "✨ 萌芽作品集 ✨",
	SiteDesc:       "🎨 展示个人制作的一些小创意和小项目，欢迎交流讨论 💬",
	Author:         "👨‍💻 by-树萌芽",
	ContactEmail:   "3205788256@qq.com",
	ThemeColor:     "#81c784",
	PageSize:       6,
	EnableSearch:   true,
	EnableCategory: true,
	Icp:            "📄 蜀ICP备2025151694号",
	Footer:         "✨ 萌芽作品集 ✨ | Copyright © 2025-2025 smy ",
	Logo:           "assets/logo.png",
}

// SettingsService manages the site-wide settings file.
type SettingsService struct {
	cfg *config.Config
}

// NewSettingsService creates a SettingsService with the given config.
func NewSettingsService(cfg *config.Config) *SettingsService {
	return &SettingsService{cfg: cfg}
}

// Load reads settings.json, returning built-in defaults when the file is absent or malformed.
func (s *SettingsService) Load() (*model.Settings, error) {
	path := filepath.Join(s.cfg.ConfigDir, "settings.json")
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			d := defaultSettings
			return &d, nil
		}
		return nil, err
	}
	var settings model.Settings
	if err := json.Unmarshal(data, &settings); err != nil {
		d := defaultSettings
		return &d, nil
	}
	return &settings, nil
}
