package db

import (
	"context"
	"fmt"
)

// GetSetting returns the value of a panel_settings key, or empty string if
// the key isn't present (caller treats empty as "unset / disabled / default").
func (db *DB) GetSetting(ctx context.Context, key string) (string, error) {
	var v string
	err := db.pool.QueryRow(ctx, `SELECT value FROM panel_settings WHERE key = $1`, key).Scan(&v)
	if err != nil {
		// pgx returns ErrNoRows when key missing — surface as empty, not error.
		// Settings are always optional from the caller's POV.
		if err.Error() == "no rows in result set" {
			return "", nil
		}
		return "", fmt.Errorf("get setting %q: %w", key, err)
	}
	return v, nil
}

// SetSetting upserts a panel_settings row.
func (db *DB) SetSetting(ctx context.Context, key, value string) error {
	_, err := db.pool.Exec(ctx, `
		INSERT INTO panel_settings (key, value) VALUES ($1, $2)
		ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
	`, key, value)
	if err != nil {
		return fmt.Errorf("set setting %q: %w", key, err)
	}
	return nil
}

// ListSettings dumps every key→value, used by the admin settings page to
// populate fields. Keep this small — it's not paginated.
func (db *DB) ListSettings(ctx context.Context) (map[string]string, error) {
	rows, err := db.pool.Query(ctx, `SELECT key, value FROM panel_settings`)
	if err != nil {
		return nil, fmt.Errorf("list settings: %w", err)
	}
	defer rows.Close()
	out := map[string]string{}
	for rows.Next() {
		var k, v string
		if err := rows.Scan(&k, &v); err != nil {
			return nil, fmt.Errorf("scan setting: %w", err)
		}
		out[k] = v
	}
	return out, rows.Err()
}
