package storage

import (
	"context"
	"fmt"

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

type BuffDebuffConfigStore struct {
	pool *pgxpool.Pool
}

func NewBuffDebuffConfigStore(pool *pgxpool.Pool) *BuffDebuffConfigStore {
	return &BuffDebuffConfigStore{pool: pool}
}

func (s *BuffDebuffConfigStore) LoadBuffDebuffConfigPayload(ctx context.Context) ([]byte, error) {
	var payload []byte
	err := s.pool.QueryRow(ctx, `SELECT payload FROM buff_debuff_config WHERE id = TRUE`).Scan(&payload)
	if err != nil {
		return nil, fmt.Errorf("load buff/debuff config payload: %w", err)
	}
	return payload, nil
}

func (s *BuffDebuffConfigStore) SaveBuffDebuffConfigPayload(ctx context.Context, payload []byte) error {
	_, err := s.pool.Exec(ctx, `
		UPDATE buff_debuff_config
		SET payload = $1::jsonb, updated_at = now()
		WHERE id = TRUE
	`, payload)
	if err != nil {
		return fmt.Errorf("save buff/debuff config payload: %w", err)
	}
	return nil
}
