package service import ( "context" "encoding/json" "github.com/calendarapi/internal/models" "github.com/calendarapi/internal/repository" "github.com/calendarapi/internal/utils" "github.com/google/uuid" ) type TaskWebhookCreateRequest struct { URL string Events []string Secret *string } func (s *TaskWebhookService) Create(ctx context.Context, userID uuid.UUID, req TaskWebhookCreateRequest) (*models.TaskWebhook, error) { if req.URL == "" { return nil, models.NewValidationError("url is required") } eventsJSON, _ := json.Marshal(req.Events) if req.Events == nil { eventsJSON = []byte("[]") } id := uuid.New() wh, err := s.queries.CreateTaskWebhook(ctx, repository.CreateTaskWebhookParams{ ID: utils.ToPgUUID(id), OwnerID: utils.ToPgUUID(userID), Url: req.URL, Column4: eventsJSON, Secret: utils.ToPgTextPtr(req.Secret), }) if err != nil { return nil, models.ErrInternal } return taskWebhookFromDB(wh), nil } func (s *TaskWebhookService) List(ctx context.Context, userID uuid.UUID) ([]models.TaskWebhook, error) { rows, err := s.queries.ListTaskWebhooksByOwner(ctx, utils.ToPgUUID(userID)) if err != nil { return nil, models.ErrInternal } webhooks := make([]models.TaskWebhook, 0, len(rows)) for _, r := range rows { webhooks = append(webhooks, *taskWebhookFromDB(r)) } return webhooks, nil } func (s *TaskWebhookService) Delete(ctx context.Context, userID uuid.UUID, webhookID uuid.UUID) error { return s.queries.DeleteTaskWebhook(ctx, repository.DeleteTaskWebhookParams{ ID: utils.ToPgUUID(webhookID), OwnerID: utils.ToPgUUID(userID), }) } func taskWebhookFromDB(wh repository.TaskWebhook) *models.TaskWebhook { w := &models.TaskWebhook{ ID: utils.FromPgUUID(wh.ID), OwnerID: utils.FromPgUUID(wh.OwnerID), URL: wh.Url, CreatedAt: utils.FromPgTimestamptz(wh.CreatedAt), } if len(wh.Events) > 0 { json.Unmarshal(wh.Events, &w.Events) } if wh.Secret.Valid { w.Secret = &wh.Secret.String } return w }