package handler import ( "net/http" "strconv" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v5/pgxpool" "github.com/mattnite/cairn/internal/models" ) type CampaignHandler struct { Pool *pgxpool.Pool } func (h *CampaignHandler) List(c *gin.Context) { limit, _ := strconv.Atoi(c.Query("limit")) offset, _ := strconv.Atoi(c.Query("offset")) if limit <= 0 { limit = 50 } campaigns, total, err := models.ListCampaigns(c.Request.Context(), h.Pool, c.Query("repository_id"), limit, offset) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } if campaigns == nil { campaigns = []models.Campaign{} } c.JSON(http.StatusOK, gin.H{ "campaigns": campaigns, "total": total, "limit": limit, "offset": offset, }) } func (h *CampaignHandler) Detail(c *gin.Context) { id := c.Param("id") campaign, err := models.GetCampaign(c.Request.Context(), h.Pool, id) if err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "campaign not found"}) return } c.JSON(http.StatusOK, campaign) } type CreateCampaignRequest struct { Repository string `json:"repository" binding:"required"` Owner string `json:"owner" binding:"required"` Name string `json:"name" binding:"required"` Type string `json:"type" binding:"required"` } func (h *CampaignHandler) Create(c *gin.Context) { var req CreateCampaignRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } ctx := c.Request.Context() repo, err := models.GetOrCreateRepository(ctx, h.Pool, req.Owner, req.Repository) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } campaign, err := models.CreateCampaign(ctx, h.Pool, models.CreateCampaignParams{ RepositoryID: repo.ID, Name: req.Name, Type: req.Type, }) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusCreated, campaign) } func (h *CampaignHandler) Finish(c *gin.Context) { id := c.Param("id") if err := models.FinishCampaign(c.Request.Context(), h.Pool, id); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"status": "finished"}) }