package backend

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

func (a *App) getSettingsPath() (string, error) {
	configDir, err := os.UserConfigDir()
	if err != nil {
		return "", err
	}
	appConfigDir := filepath.Join(configDir, "quickly")
	if err := os.MkdirAll(appConfigDir, 0755); err != nil {
		return "", err
	}
	return filepath.Join(appConfigDir, "settings.json"), nil
}

func (a *App) loadSettings() {
	settingsPath, err := a.getSettingsPath()
	if err != nil {
		fmt.Println("Error getting settings path:", err)
		a.settings = Settings{
			Theme:                   "light",
			Language:                "zh-CN",
			Notifications:           true,
			AutoStart:               false,
			MysqlModelPath:          "",
			DefaultQueryPackagePath: "",
			ModelBasePath:           "",
			SwaggerFilePath:         "",
			Databases:               []DatabaseConfig{},
			Projects:                []ProjectConfig{},
		}
		return
	}

	data, err := os.ReadFile(settingsPath)
	if err != nil {
		if os.IsNotExist(err) {
			a.settings = Settings{
				Theme:                   "light",
				Language:                "zh-CN",
				Notifications:           true,
				AutoStart:               false,
				MysqlModelPath:          "",
				DefaultQueryPackagePath: "",
				ModelBasePath:           "",
				SwaggerFilePath:         "",
				Databases:               []DatabaseConfig{},
				Projects:                []ProjectConfig{},
			}
			return
		}
		fmt.Println("Error reading settings file:", err)
		return
	}

	if err := json.Unmarshal(data, &a.settings); err != nil {
		fmt.Println("Error parsing settings file:", err)
		a.settings = Settings{
			Theme:                   "light",
			Language:                "zh-CN",
			Notifications:           true,
			AutoStart:               false,
			MysqlModelPath:          "",
			DefaultQueryPackagePath: "",
			ModelBasePath:           "",
			SwaggerFilePath:         "",
			Databases:               []DatabaseConfig{},
			Projects:                []ProjectConfig{},
		}
	}
}

func (a *App) saveSettings() error {
	settingsPath, err := a.getSettingsPath()
	if err != nil {
		return fmt.Errorf("error getting settings path: %w", err)
	}

	data, err := json.MarshalIndent(a.settings, "", "  ")
	if err != nil {
		return fmt.Errorf("error marshaling settings: %w", err)
	}

	if err := os.WriteFile(settingsPath, data, 0644); err != nil {
		return fmt.Errorf("error writing settings file: %w", err)
	}

	return nil
}

func (a *App) GetSettings() Settings {
	return a.settings
}

func (a *App) SaveSettings(settings Settings) error {
	a.settings = settings
	return a.saveSettings()
}
