;;; HTTP request
;;; Copyright (C) 2026 David Thompson <dave@spritely.institute>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;;    http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.

;;; Commentary:
;;;
;;; HTTP Request bindings.
;;;
;;; Code:

(define-module (web request)
  #:use-module (hoot ffi)
  #:use-module (hoot match)
  #:use-module (hoot typed-arrays)
  #:use-module (rnrs bytevectors)
  #:use-module (web uri)
  #:export (build-request
            request?
            request-method))

;; -> null
(define-foreign empty-body
  "rt" "request_empty_body" -> (ref null extern))
;; string string maybe<Uint8Array> -> Request
(define-foreign make-request
  "rt" "make_request" (ref string) (ref string) (ref null extern) -> (ref extern))
;; Request -> i32
(define-foreign request-test
  "rt" "request_test" (ref extern) -> i32)
;; Request -> string
(define-foreign request-method
  "rt" "request_method" (ref extern) -> (ref string))

;; We can't easily match Guile's request API because we can't
;; read/write requests to/from arbitrary ports.
;;
;; TODO: Support headers by binding Headers class.
(define* (build-request uri #:key (method 'GET) (headers '()) body)
  (when (and (not body) (memq method '(POST PUT)))
    (error "missing body for POST/PUT request"))
  (unless (null? headers)
    (error "request headers unsupported"))
  (make-request (symbol->string method)
                (uri->string uri)
                (match body
                  (#f (empty-body))
                  ((? bytevector?)
                   (bytevector->uint8array body))
                  ((? string?)
                   (bytevector->uint8array (string->utf8 body))))))

(define (request? obj)
  (and (external? obj) (eq? (request-test obj) 1)))
