import http from "k6/http"
import { check, sleep } from "k6"
import { Rate } from "k6/metrics"
import { __ENV } from "k6/env"

const errorRate = new Rate("errors")

export const options = {
  stages: [
    { duration: "30s", target: 5 },
    { duration: "1m", target: 20 },
    { duration: "30s", target: 0 },
  ],
  thresholds: {
    http_req_duration: ["p(95)<1000"],
    errors: ["rate<0.15"],
  },
}

const BASE_URL = __ENV.BASE_URL || "http://localhost:3000"

export default function () {
  // Request signed URL for upload
  const response = http.post(
    `${BASE_URL}/api/upload/sign`,
    JSON.stringify({
      filename: "test-audio.mp3",
      contentType: "audio/mpeg",
      fileSize: 1024 * 1024, // 1MB
      fileType: "audio",
    }),
    {
      headers: { "Content-Type": "application/json" },
    },
  )

  check(response, {
    "sign status is 200": (r) => r.status === 200,
    "sign response is JSON": (r) => r.headers["Content-Type"]?.includes("application/json"),
    "sign has signedUrl": (r) => {
      if (r.status === 200) {
        const data = JSON.parse(r.body)
        return data.success && data.data.signedUrl !== undefined
      }
      return false
    },
  })
  errorRate.add(response.status !== 200)

  sleep(2)
}
