package repository

import (
	"baron-sso-backend/internal/domain"
	"context"

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

type clientSecretRepository struct {
	db *gorm.DB
}

func NewClientSecretRepository(db *gorm.DB) domain.ClientSecretRepository {
	return &clientSecretRepository{db: db}
}

func (r *clientSecretRepository) Upsert(ctx context.Context, clientID, secret string) error {
	cs := domain.ClientSecret{
		ClientID:     clientID,
		ClientSecret: secret,
	}
	return r.db.WithContext(ctx).Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "client_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"client_secret", "updated_at"}),
	}).Create(&cs).Error
}

func (r *clientSecretRepository) GetByID(ctx context.Context, clientID string) (string, error) {
	var cs domain.ClientSecret
	if err := r.db.WithContext(ctx).Where("client_id = ?", clientID).First(&cs).Error; err != nil {
		return "", err
	}
	return cs.ClientSecret, nil
}

func (r *clientSecretRepository) Delete(ctx context.Context, clientID string) error {
	return r.db.WithContext(ctx).Where("client_id = ?", clientID).Delete(&domain.ClientSecret{}).Error
}
