(ns ajet.chat.shared.storage-integration-test
  (:require [clojure.test :refer [deftest testing is use-fixtures]]
            [ajet.chat.shared.storage :as storage]
            [ajet.chat.test-helpers :as th]))

(use-fixtures :once th/with-s3-suite)

(def ^:private test-bucket (:bucket th/test-minio-config))

;;; ---------------------------------------------------------------------------
;;; Upload / Download / Delete tests
;;; ---------------------------------------------------------------------------

(deftest upload-and-download
  (let [key  (str "test/" (th/uuid) "/file.txt")
        data (.getBytes "hello world" "UTF-8")]
    (storage/upload! th/*s3* test-bucket key data "text/plain")
    (let [downloaded (storage/download th/*s3* test-bucket key)]
      (is (some? downloaded))
      (is (= "hello world" (String. downloaded "UTF-8"))))
    (storage/delete! th/*s3* test-bucket key)))

(deftest download-nonexistent-returns-nil
  (let [result (storage/download th/*s3* test-bucket (str "nonexistent/" (th/uuid)))]
    (is (nil? result))))

(deftest delete-is-idempotent
  (let [key (str "test/" (th/uuid) "/gone.txt")]
    (is (nil? (storage/delete! th/*s3* test-bucket key)))))

(deftest upload-and-delete
  (let [key  (str "test/" (th/uuid) "/delete-me.txt")
        data (.getBytes "temp" "UTF-8")]
    (storage/upload! th/*s3* test-bucket key data "text/plain")
    (storage/delete! th/*s3* test-bucket key)
    (is (nil? (storage/download th/*s3* test-bucket key)))))

;;; ---------------------------------------------------------------------------
;;; Presigned URL test
;;; ---------------------------------------------------------------------------

(deftest presigned-url-generation
  (let [presigner (storage/make-presigner th/test-minio-config)
        key       (str "test/" (th/uuid) "/presigned.txt")
        data      (.getBytes "content" "UTF-8")]
    (try
      (storage/upload! th/*s3* test-bucket key data "text/plain")
      (let [url (storage/presigned-url presigner test-bucket key)]
        (is (string? url))
        (is (re-find #"http" url))
        (is (re-find #"presigned" url)))
      (finally
        (storage/delete! th/*s3* test-bucket key)
        (.close presigner)))))

;;; ---------------------------------------------------------------------------
;;; Ensure bucket is idempotent
;;; ---------------------------------------------------------------------------

(deftest ensure-bucket-idempotent
  (is (nil? (storage/ensure-bucket! th/*s3* test-bucket))))
