// Package lidarrconfig is a thin wrapper over the singleton lidarr_config
// row. Get returns a typed Config; Save updates it. Callers branch on
// Config.Enabled — never on raw NULL fields.
package lidarrconfig

import (
	"context"
	"fmt"

	"github.com/jackc/pgx/v5/pgxpool"

	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)

// Config is the typed projection of lidarr_config (no NULL fields exposed
// to callers — empty strings / zero ints carry the "unset" meaning).
type Config struct {
	Enabled                  bool
	BaseURL                  string
	APIKey                   string
	DefaultQualityProfileID  int
	DefaultMetadataProfileID int
	DefaultRootFolderPath    string
}

// Service reads and writes the singleton.
type Service struct {
	pool *pgxpool.Pool
}

func New(pool *pgxpool.Pool) *Service { return &Service{pool: pool} }

func (s *Service) Get(ctx context.Context) (Config, error) {
	row, err := dbq.New(s.pool).GetLidarrConfig(ctx)
	if err != nil {
		return Config{}, fmt.Errorf("lidarrconfig: %w", err)
	}
	cfg := Config{Enabled: row.Enabled}
	if row.BaseUrl != nil {
		cfg.BaseURL = *row.BaseUrl
	}
	if row.ApiKey != nil {
		cfg.APIKey = *row.ApiKey
	}
	if row.DefaultQualityProfileID != nil {
		cfg.DefaultQualityProfileID = int(*row.DefaultQualityProfileID)
	}
	if row.DefaultMetadataProfileID != nil {
		cfg.DefaultMetadataProfileID = int(*row.DefaultMetadataProfileID)
	}
	if row.DefaultRootFolderPath != nil {
		cfg.DefaultRootFolderPath = *row.DefaultRootFolderPath
	}
	return cfg, nil
}

// Save writes the entire row. Callers pass the full Config they want
// stored — this is not a partial update.
func (s *Service) Save(ctx context.Context, cfg Config) error {
	var (
		baseURL  = strPtr(cfg.BaseURL)
		apiKey   = strPtr(cfg.APIKey)
		qpID     = int32Ptr(cfg.DefaultQualityProfileID)
		mpID     = int32Ptr(cfg.DefaultMetadataProfileID)
		rootPath = strPtr(cfg.DefaultRootFolderPath)
	)
	_, err := dbq.New(s.pool).UpdateLidarrConfig(ctx, dbq.UpdateLidarrConfigParams{
		Enabled:                  cfg.Enabled,
		BaseUrl:                  baseURL,
		ApiKey:                   apiKey,
		DefaultQualityProfileID:  qpID,
		DefaultMetadataProfileID: mpID,
		DefaultRootFolderPath:    rootPath,
	})
	if err != nil {
		return fmt.Errorf("lidarrconfig: %w", err)
	}
	return nil
}

func strPtr(s string) *string {
	if s == "" {
		return nil
	}
	return &s
}

func int32Ptr(i int) *int32 {
	if i == 0 {
		return nil
	}
	v := int32(i)
	return &v
}
