package realname

import (
	"time"

	"hfb_sys/backend/internal/model"

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

type Repository struct {
	db *gorm.DB
}

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

func (r *Repository) FindByUserID(userID uint64) (*model.UserRealname, error) {
	var record model.UserRealname
	if err := r.db.Where("user_id = ?", userID).First(&record).Error; err != nil {
		return nil, err
	}
	return &record, nil
}

func (r *Repository) SaveResult(userID uint64, provider string, result ProviderResult) (*model.UserRealname, error) {
	record := model.UserRealname{
		UserID:          userID,
		Provider:        provider,
		ProviderOrderNo: result.ProviderOrderNo,
		Status:          result.Status,
		MaskedName:      result.MaskedName,
		MaskedIDNo:      result.MaskedIDNo,
		VerifiedAt:      result.VerifiedAt,
		FailReason:      result.FailReason,
	}

	err := r.db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Clauses(clause.OnConflict{
			Columns: []clause.Column{{Name: "user_id"}},
			DoUpdates: clause.Assignments(map[string]any{
				"provider":          record.Provider,
				"provider_order_no": record.ProviderOrderNo,
				"status":            record.Status,
				"masked_name":       record.MaskedName,
				"masked_id_no":      record.MaskedIDNo,
				"verified_at":       record.VerifiedAt,
				"fail_reason":       record.FailReason,
				"updated_at":        time.Now(),
			}),
		}).Create(&record).Error; err != nil {
			return err
		}

		userStatus := StatusRejected
		if result.Status == StatusVerified {
			userStatus = "verified"
		}
		if result.Status == StatusPending {
			userStatus = "pending"
		}
		return tx.Model(&model.User{}).Where("id = ?", userID).Update("realname_status", userStatus).Error
	})
	if err != nil {
		return nil, err
	}
	return r.FindByUserID(userID)
}
