package main

import (
	"encoding/json"
	"fmt"
	"strings"

	wruntime "github.com/wailsapp/wails/v2/pkg/runtime"
)

// keyAwardsTracked holds the PER-PROFILE list of award codes the operator wants
// to follow (JSON array of award.Def.Code). Award definitions themselves are
// global (keyAwardDefs, shared across profiles), but WHICH awards a station
// tracks is a per-profile choice — a DX profile follows DXCC/WPX, a POTA profile
// follows POTA/WWFF. An empty/unset list means "track them all" so the Awards
// tab is never blank before the operator has picked anything.
const keyAwardsTracked = "awards.tracked"

// GetTrackedAwards returns the active profile's followed award codes. An empty
// slice means the operator has not narrowed the list — the Awards tab then shows
// every award.
func (a *App) GetTrackedAwards() ([]string, error) {
	out := []string{}
	if a.settings == nil {
		return out, nil
	}
	s, _ := a.settings.Get(a.ctx, keyAwardsTracked)
	if strings.TrimSpace(s) == "" {
		return out, nil
	}
	if err := json.Unmarshal([]byte(s), &out); err != nil {
		return []string{}, nil
	}
	return out, nil
}

// SaveTrackedAwards persists the followed award codes for the active profile and
// notifies the Awards tab to re-filter its list. Codes are stored verbatim; the
// Awards tab intersects them with the live award definitions, so a code that no
// longer exists is simply ignored (not an error).
func (a *App) SaveTrackedAwards(codes []string) error {
	if a.settings == nil {
		return fmt.Errorf("db not initialized")
	}
	if codes == nil {
		codes = []string{}
	}
	b, err := json.Marshal(codes)
	if err != nil {
		return err
	}
	if err := a.settings.Set(a.ctx, keyAwardsTracked, string(b)); err != nil {
		return err
	}
	wruntime.EventsEmit(a.ctx, "awards:tracked-changed")
	return nil
}
