package payments

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/go-jet/jet/v2/postgres"

	"scrabble/backend/internal/postgres/jet/payments/model"
	"scrabble/backend/internal/postgres/jet/payments/table"
)

// Store is the Postgres-backed query surface for the payments schema. It is the
// only place in the backend that issues SQL against payments.* (an
// import-boundary test enforces it), so the domain stays extractable into its
// own database. It fronts the materialized balances/benefits tables with an
// in-process write-through cache (see cache.go) so hot reads issue no query on
// the steady-state path.
type Store struct {
	db    *sql.DB
	cache *walletCache
}

// NewStore constructs a Store wrapping db, with an empty read cache.
func NewStore(db *sql.DB) *Store { return &Store{db: db, cache: newWalletCache()} }

// Ping verifies the payments schema is reachable by reading the singleton config
// row. It is the data-foundation health check; the wallet query surface arrives
// with the currency mechanics.
func (s *Store) Ping(ctx context.Context) error {
	var row model.Config
	if err := postgres.SELECT(table.Config.AllColumns).
		FROM(table.Config).
		LIMIT(1).
		QueryContext(ctx, s.db, &row); err != nil {
		return fmt.Errorf("payments: ping: %w", err)
	}
	return nil
}
