package repositories import ( "context" "veza-backend-api/internal/models" "github.com/google/uuid" "gorm.io/gorm" ) // WebhookRepository defines the interface for webhook data access type WebhookRepository interface { Create(ctx context.Context, webhook *models.Webhook) error ListByUserID(ctx context.Context, userID uuid.UUID) ([]models.Webhook, error) GetByIDAndUserID(ctx context.Context, webhookID, userID uuid.UUID) (*models.Webhook, error) FindActiveByEvent(ctx context.Context, event string, userID *uuid.UUID) ([]models.Webhook, error) Update(ctx context.Context, webhook *models.Webhook) error Delete(ctx context.Context, webhookID, userID uuid.UUID) (int64, error) GetByAPIKey(ctx context.Context, apiKey string) (*models.Webhook, error) } type webhookRepository struct { db *gorm.DB } // NewWebhookRepository creates a new WebhookRepository func NewWebhookRepository(db *gorm.DB) WebhookRepository { return &webhookRepository{db: db} } func (r *webhookRepository) Create(ctx context.Context, webhook *models.Webhook) error { return r.db.WithContext(ctx).Create(webhook).Error } func (r *webhookRepository) ListByUserID(ctx context.Context, userID uuid.UUID) ([]models.Webhook, error) { var webhooks []models.Webhook if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Find(&webhooks).Error; err != nil { return nil, err } return webhooks, nil } func (r *webhookRepository) GetByIDAndUserID(ctx context.Context, webhookID, userID uuid.UUID) (*models.Webhook, error) { var webhook models.Webhook if err := r.db.WithContext(ctx).Where("id = ? AND user_id = ?", webhookID, userID).First(&webhook).Error; err != nil { return nil, err } return &webhook, nil } func (r *webhookRepository) FindActiveByEvent(ctx context.Context, event string, userID *uuid.UUID) ([]models.Webhook, error) { var webhooks []models.Webhook query := r.db.WithContext(ctx).Where("active = ? AND events @> ARRAY[?]", true, event) if userID != nil { query = query.Where("user_id = ?", *userID) } if err := query.Find(&webhooks).Error; err != nil { return nil, err } return webhooks, nil } func (r *webhookRepository) Update(ctx context.Context, webhook *models.Webhook) error { return r.db.WithContext(ctx).Save(webhook).Error } func (r *webhookRepository) Delete(ctx context.Context, webhookID, userID uuid.UUID) (int64, error) { result := r.db.WithContext(ctx).Where("id = ? AND user_id = ?", webhookID, userID).Delete(&models.Webhook{}) return result.RowsAffected, result.Error } func (r *webhookRepository) GetByAPIKey(ctx context.Context, apiKey string) (*models.Webhook, error) { var webhook models.Webhook if err := r.db.WithContext(ctx).Where("api_key = ? AND active = ?", apiKey, true).First(&webhook).Error; err != nil { return nil, err } return &webhook, nil }