package particle

import (
	"context"

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

type ProcessingRepository interface {
	IsProcessed(ctx context.Context, particleID string) (bool, error)
	MarkProcessed(ctx context.Context, particleID string) error
}

type processingRepositoryImpl struct {
	pool *pgxpool.Pool
}

func NewProcessingRepository(pool *pgxpool.Pool) ProcessingRepository {
	return &processingRepositoryImpl{pool: pool}
}

func (r *processingRepositoryImpl) IsProcessed(ctx context.Context, particleID string) (bool, error) {
	var exists bool
	err := r.pool.QueryRow(ctx,
		`SELECT EXISTS(SELECT 1 FROM processed_particles WHERE particle_id = $1)`,
		particleID,
	).Scan(&exists)
	return exists, err
}

func (r *processingRepositoryImpl) MarkProcessed(ctx context.Context, particleID string) error {
	_, err := r.pool.Exec(ctx,
		`INSERT INTO processed_particles (particle_id) VALUES ($1) ON CONFLICT (particle_id) DO NOTHING`,
		particleID,
	)
	return err
}
