// internal/repositories/claim_verification_repo.go
package repositories

import (
	"errors"
	"lost-and-found/internal/models"

	"gorm.io/gorm"
)

type ClaimVerificationRepository struct {
	db *gorm.DB
}

func NewClaimVerificationRepository(db *gorm.DB) *ClaimVerificationRepository {
	return &ClaimVerificationRepository{db: db}
}

// Create creates a new claim verification
func (r *ClaimVerificationRepository) Create(verification *models.ClaimVerification) error {
	return r.db.Create(verification).Error
}

// FindByID finds claim verification by ID
func (r *ClaimVerificationRepository) FindByID(id uint) (*models.ClaimVerification, error) {
	var verification models.ClaimVerification
	err := r.db.Preload("Claim").First(&verification, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("claim verification not found")
		}
		return nil, err
	}
	return &verification, nil
}

// FindByClaimID finds claim verification by claim ID
func (r *ClaimVerificationRepository) FindByClaimID(claimID uint) (*models.ClaimVerification, error) {
	var verification models.ClaimVerification
	err := r.db.Where("claim_id = ?", claimID).Preload("Claim").First(&verification).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil // Return nil if not found (not an error)
		}
		return nil, err
	}
	return &verification, nil
}

// Update updates claim verification
func (r *ClaimVerificationRepository) Update(verification *models.ClaimVerification) error {
	return r.db.Save(verification).Error
}

// Delete deletes a claim verification
func (r *ClaimVerificationRepository) Delete(id uint) error {
	return r.db.Delete(&models.ClaimVerification{}, id).Error
}

// FindHighMatches finds high match verifications (>= 70%)
func (r *ClaimVerificationRepository) FindHighMatches() ([]models.ClaimVerification, error) {
	var verifications []models.ClaimVerification
	err := r.db.Where("similarity_score >= ?", 70.0).
		Preload("Claim").Preload("Claim.Item").Preload("Claim.User").
		Order("similarity_score DESC").Find(&verifications).Error
	return verifications, err
}