package config

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

// FeedsDocument is the YAML shape of feeds.yaml. The URL with the
// embedded passkey is NEVER stored in the YAML — only the metadata. The
// runtime URL lives in the age-encrypted secrets store under
// `feed:<id>:url` (see internal/integrations/feeds/store.go).
type FeedsDocument struct {
	Feeds []FeedEntry `yaml:"feeds"`
}

// FeedEntry pins one RSS/Atom subscription. `tracker_id` is the optional
// hint that tells the on-demand fetcher which tracker's session cookies
// to attach when downloading individual .torrent files from the feed's
// item URLs (so /api/torrents/add-from-url's cookie-attach path can fire
// without ambiguity). Empty = let the auto-detector match by URL host.
type FeedEntry struct {
	ID        string `yaml:"id"`
	Name      string `yaml:"name"`
	TrackerID string `yaml:"tracker_id,omitempty"`
	// Disabled feeds skip even on-demand fetches; the SPA still lists
	// them so the operator can flip the flag without editing YAML. Mirrors
	// the trackers / torrent-clients pattern.
	Enabled bool `yaml:"enabled"`
}

// LoadFeedsFromDir reads <dir>/feeds.yaml. Missing file is NOT an error —
// returns an empty document so a fresh deploy with no feeds configured
// boots cleanly.
func LoadFeedsFromDir(dir string) (*FeedsDocument, error) {
	path := filepath.Join(dir, "feeds.yaml")
	b, err := os.ReadFile(path)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return &FeedsDocument{}, nil
		}
		return nil, fmt.Errorf("feeds config: %w", err)
	}
	var doc FeedsDocument
	if err := yaml.Unmarshal(b, &doc); err != nil {
		return nil, fmt.Errorf("feeds config: parse: %w", err)
	}
	for i, f := range doc.Feeds {
		if f.ID == "" {
			return nil, fmt.Errorf("feeds[%d]: id required", i)
		}
	}
	return &doc, nil
}
