package storage

import (
	"context"
	"fmt"

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

type RuntimeConfigStore struct {
	pool *pgxpool.Pool
}

func NewRuntimeConfigStore(pool *pgxpool.Pool) *RuntimeConfigStore {
	return &RuntimeConfigStore{pool: pool}
}

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

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

