package repoimpl

import (
	"context"
	"gorm.io/gorm"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/repo"
	"voucher/internal/data"
	"voucher/internal/data/model"
)

// ProductRepoImpl .
type ProductRepoImpl struct {
	Base[model.Product, bo.ProductBo]
	db *data.Db
}

// NewProductRepoImpl .
func NewProductRepoImpl() repo.ProductRepo {
	return &ProductRepoImpl{}
}

func (p *ProductRepoImpl) DB(ctx context.Context) *gorm.DB {
	return p.db.DB(ctx).Model(model.Product{})
}

func (r *ProductRepoImpl) GetByPNO(ctx context.Context, PNO string) (*bo.ProductBo, error) {
	var item model.Product

	tx := r.DB(ctx).Where(model.Product{ProductNo: PNO}).Find(&item)

	if tx.Error != nil {
		return nil, tx.Error
	}
	if tx.RowsAffected == 0 {
		return nil, gorm.ErrRecordNotFound
	}

	return r.ToBo(&item), nil
}
