package pricing

import (
	"context"
	"errors"

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

	"github.com/TaruLab/keluargamart-backend/internal/db"
)

// Repository implements Store on a pgx pool (sqlc-backed).
type Repository struct {
	pool *pgxpool.Pool
}

func NewRepository(pool *pgxpool.Pool) *Repository {
	return &Repository{pool: pool}
}

// queries binds the sqlc queries to the caller's transaction, falling back to
// the pool only when the caller is not inside one.
func (r *Repository) queries(q db.DBTX) *db.Queries {
	if q == nil {
		return db.New(r.pool)
	}
	return db.New(q)
}

func (r *Repository) PricingProduct(ctx context.Context, q db.DBTX, id int64) (db.GetPricingProductRow, error) {
	row, err := r.queries(q).GetPricingProduct(ctx, id)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return db.GetPricingProductRow{}, ErrProductNotFound
		}
		return db.GetPricingProductRow{}, err
	}
	return row, nil
}

func (r *Repository) PricingProductUnit(ctx context.Context, q db.DBTX, id int64) (db.GetPricingProductUnitRow, error) {
	row, err := r.queries(q).GetPricingProductUnit(ctx, id)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return db.GetPricingProductUnitRow{}, ErrUnitNotFound
		}
		return db.GetPricingProductUnitRow{}, err
	}
	return row, nil
}

func (r *Repository) PricingBaseUnit(ctx context.Context, q db.DBTX, productID int64) (db.GetPricingBaseUnitRow, error) {
	row, err := r.queries(q).GetPricingBaseUnit(ctx, productID)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return db.GetPricingBaseUnitRow{}, ErrUnitNotFound
		}
		return db.GetPricingBaseUnitRow{}, err
	}
	return row, nil
}
