// Filename: internal/repository/key_crypto.go
package repository

import (
	"fmt"
	"gemini-balancer/internal/models"
)

func (r *gormKeyRepository) decryptKey(key *models.APIKey) error {
	if key == nil || key.EncryptedKey == "" {
		return nil // Nothing to decrypt
	}
	// Avoid re-decrypting if plaintext already exists
	if key.APIKey != "" {
		return nil
	}
	plaintext, err := r.crypto.Decrypt(key.EncryptedKey)
	if err != nil {
		return fmt.Errorf("failed to decrypt key ID %d: %w", key.ID, err)
	}
	key.APIKey = plaintext
	return nil
}

func (r *gormKeyRepository) decryptKeys(keys []models.APIKey) error {
	for i := range keys {
		if err := r.decryptKey(&keys[i]); err != nil {
			// In a batch operation, we log the error but allow the rest to proceed.
			r.logger.Errorf("Batch decrypt error for key index %d: %v", i, err)
		}
	}
	return nil
}

// Decrypt 实现了 KeyRepository 接口
func (r *gormKeyRepository) Decrypt(key *models.APIKey) error {
	if key == nil || len(key.EncryptedKey) == 0 {
		return nil // Nothing to decrypt
	}
	// Avoid re-decrypting if plaintext already exists
	if key.APIKey != "" {
		return nil
	}
	plaintext, err := r.crypto.Decrypt(key.EncryptedKey)
	if err != nil {
		return fmt.Errorf("failed to decrypt key ID %d: %w", key.ID, err)
	}
	key.APIKey = plaintext
	return nil
}

// DecryptBatch 实现了 KeyRepository 接口
func (r *gormKeyRepository) DecryptBatch(keys []models.APIKey) error {
	for i := range keys {
		// This delegates to the robust single-key decryption logic.
		if err := r.Decrypt(&keys[i]); err != nil {
			// In a batch operation, we log the error but allow the rest to proceed.
			r.logger.Errorf("Batch decrypt error for key index %d (ID: %d): %v", i, keys[i].ID, err)
		}
	}
	return nil
}
