package repository

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

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

type PurchaseRepository interface {
	Create(ctx context.Context, purchase *models.Purchase) (*models.Purchase, error)
	GetByUserID(ctx context.Context, userID int64) ([]models.Purchase, error)
}

type postgresPurchaseRepository struct {
	db *pgxpool.Pool
}

func NewPurchaseRepository(db *pgxpool.Pool) PurchaseRepository {
	return &postgresPurchaseRepository{db: db}
}

func (r *postgresPurchaseRepository) Create(ctx context.Context, purchase *models.Purchase) (*models.Purchase, error) {
	query := `
		INSERT INTO purchases (user_id, reward_id, stars_spent, status)
		VALUES ($1, $2, $3, $4)
		RETURNING id, purchased_at
	`
	querier := getQuerier(ctx, r.db)
	err := querier.QueryRow(ctx, query,
		purchase.UserID, purchase.RewardID, purchase.StarsSpent, purchase.Status,
	).Scan(&purchase.ID, &purchase.PurchasedAt)

	if err != nil {
		return nil, err
	}
	return purchase, nil
}

// GetByUserID retrieves all purchases for a given user, ordered by most recent first.
func (r *postgresPurchaseRepository) GetByUserID(ctx context.Context, userID int64) ([]models.Purchase, error) {
	query := `
		SELECT id, user_id, reward_id, stars_spent, purchased_at, status
		FROM purchases
		WHERE user_id = $1
		ORDER BY purchased_at DESC
	`
	rows, err := r.db.Query(ctx, query, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var purchases []models.Purchase
	for rows.Next() {
		var p models.Purchase
		if err := rows.Scan(&p.ID, &p.UserID, &p.RewardID, &p.StarsSpent, &p.PurchasedAt, &p.Status); err != nil {
			return nil, err
		}
		purchases = append(purchases, p)
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	if purchases == nil {
		return []models.Purchase{}, nil
	}

	return purchases, nil
}
