package idempotency import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "strings" "time" "cotizador/internal/auth" "cotizador/internal/db" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) const TTL = 24 * time.Hour type HandlerFunc func(rawBody []byte) (statusCode int, responseBody any) // Execute wraps a mutating endpoint with Idempotency-Key support (24h TTL, SHA-256 body hash). func Execute(ctx context.Context, pool *pgxpool.Pool, w http.ResponseWriter, r *http.Request, actor *auth.Actor, fn HandlerFunc) { rawBody, err := io.ReadAll(r.Body) if err != nil { writeJSON(w, http.StatusBadRequest, map[string]any{"error": "No se pudo leer el cuerpo de la solicitud"}) return } r.Body = io.NopCloser(bytes.NewReader(rawBody)) idemHeader := strings.TrimSpace(r.Header.Get("Idempotency-Key")) if idemHeader == "" { status, body := fn(rawBody) writeJSON(w, status, body) return } actorKey := "user:" + actor.UserID if actor.IsAgent() { actorKey = "agent:" + actor.KeyID } composedKey := fmt.Sprintf("%s:%s:%s:%s", actorKey, r.Method, r.URL.Path, idemHeader) sum := sha256.Sum256(rawBody) reqHash := hex.EncodeToString(sum[:]) var existingHash string var existingStatus int var existingBody json.RawMessage var expiraAt time.Time err = pool.QueryRow(ctx, ` SELECT "requestHash", "statusCode", "responseBody", "expiraAt" FROM "IdempotencyKey" WHERE "key" = $1 `, composedKey).Scan(&existingHash, &existingStatus, &existingBody, &expiraAt) if err == nil { if time.Now().After(expiraAt) { _, _ = pool.Exec(ctx, `DELETE FROM "IdempotencyKey" WHERE "key" = $1`, composedKey) } else { if existingHash != reqHash { writeJSON(w, http.StatusConflict, map[string]any{ "error": "Idempotency-Key ya fue usada con un cuerpo de solicitud distinto", }) return } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("X-Idempotency-Replayed", "true") w.WriteHeader(existingStatus) _, _ = w.Write(existingBody) return } } else if !errors.Is(err, pgx.ErrNoRows) { // Fall through gracefully on lookup error } status, body := fn(rawBody) bodyBytes, err := json.Marshal(body) if err != nil { bodyBytes = []byte(`{}`) } if status < 500 { _, _ = pool.Exec(ctx, ` INSERT INTO "IdempotencyKey" ("id", "key", "method", "path", "requestHash", "statusCode", "responseBody", "expiraAt") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT ("key") DO UPDATE SET "requestHash" = EXCLUDED."requestHash", "statusCode" = EXCLUDED."statusCode", "responseBody" = EXCLUDED."responseBody", "expiraAt" = EXCLUDED."expiraAt" `, db.NewID(), composedKey, r.Method, r.URL.Path, reqHash, status, bodyBytes, time.Now().Add(TTL)) } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) _, _ = w.Write(bodyBytes) } func writeJSON(w http.ResponseWriter, status int, payload any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(payload) }