package ocr

import (
	"strings"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"

	"rmser/internal/domain/ocr"

	"github.com/google/uuid"
)

type pgRepository struct {
	db *gorm.DB
}

func NewRepository(db *gorm.DB) ocr.Repository {
	return &pgRepository{db: db}
}

func (r *pgRepository) SaveMatch(rawName string, productID uuid.UUID) error {
	normalized := strings.ToLower(strings.TrimSpace(rawName))
	match := ocr.ProductMatch{
		RawName:   normalized,
		ProductID: productID,
	}

	// Upsert: если такая строка уже была, обновляем ссылку на товар
	return r.db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "raw_name"}},
		DoUpdates: clause.AssignmentColumns([]string{"product_id", "updated_at"}),
	}).Create(&match).Error
}

func (r *pgRepository) FindMatch(rawName string) (*uuid.UUID, error) {
	normalized := strings.ToLower(strings.TrimSpace(rawName))
	var match ocr.ProductMatch

	err := r.db.Where("raw_name = ?", normalized).First(&match).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}

	return &match.ProductID, nil
}
