package handler import ( "fmt" "net/http" "github.com/google/uuid" "git.kundeng.us/phoenix/textsender-api/internal/store" "git.kundeng.us/phoenix/textsender-models/pkg/contact" ) type RequestAddContact struct { PhoneNumber string `json:"phone_number"` UserId uuid.UUID `json:"user_id"` } type AddContactResponse struct { Message string `json:"message"` Data []contact.Contact `json:"data"` } type ContactHandler struct { ContactStore store.ContactStore } func NewContactHandler(str store.ContactStore) *ContactHandler { return &ContactHandler{ContactStore: str} } func (c *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } var req RequestAddContact if err := ExtractFromRequest(r, &req); err != nil { http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest) } defer r.Body.Close() newContact := contact.Contact{PhoneNumber: req.PhoneNumber, UserId: req.UserId} var statusCode int var resp AddContactResponse ctx := r.Context() if exists, err := c.ContactStore.ContactExists(ctx, newContact.PhoneNumber, newContact.UserId); err != nil { fmt.Printf("Error: %v", err) statusCode = http.StatusInternalServerError resp.Message = err.Error() } else { if exists { statusCode = http.StatusBadRequest resp.Message = "Cannot create contact" } else { if err := c.ContactStore.CreateContact(ctx, &newContact); err != nil { fmt.Printf("Error: %v", err) statusCode = http.StatusInternalServerError resp.Message = err.Error() } else { statusCode = http.StatusCreated resp.Message = "Contact created" resp.Data = append(resp.Data, newContact) } } } RespondWithJSON(w, statusCode, &resp) }