package repository

import (
	"context"
	"sno/internal/models"

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

// QRScanRepository defines the interface for QR scan data operations.
type QRScanRepository interface {
	Create(ctx context.Context, scan *models.QRScan) (*models.QRScan, error)
}

// postgresQRScanRepository implements the QRScanRepository interface.
type postgresQRScanRepository struct {
	db *pgxpool.Pool
}

// NewQRScanRepository creates a new instance of a QR scan repository.
func NewQRScanRepository(db *pgxpool.Pool) QRScanRepository {
	return &postgresQRScanRepository{db: db}
}

// Create inserts a new QR scan record into the database.
func (r *postgresQRScanRepository) Create(ctx context.Context, scan *models.QRScan) (*models.QRScan, error) {
	query := `
		INSERT INTO qr_scans (user_id, type, value, source)
		VALUES ($1, $2, $3, $4)
		RETURNING id, scanned_at
	`
	querier := getQuerier(ctx, r.db)
	err := querier.QueryRow(ctx, query,
		scan.UserID, scan.Type, scan.Value, scan.Source,
	).Scan(&scan.ID, &scan.ScannedAt)

	if err != nil {
		return nil, err
	}

	return scan, nil
}
