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: 10 },
    { duration: "1m", target: 50 },
    { duration: "30s", target: 0 },
  ],
  thresholds: {
    http_req_duration: ["p(95)<2000"],
    errors: ["rate<0.1"],
  },
}

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

export default function () {
  // Get a track first
  let response = http.get(`${BASE_URL}/api/tracks?limit=1`)
  if (response.status === 200) {
    const data = JSON.parse(response.body)
    if (data.success && data.data.length > 0) {
      const trackId = data.data[0].id

      // Test streaming without range
      response = http.get(`${BASE_URL}/api/stream/${trackId}`)
      check(response, {
        "stream status is 200": (r) => r.status === 200,
        "stream content-type is audio": (r) => r.headers["Content-Type"]?.includes("audio"),
        "stream has cache-control": (r) => r.headers["Cache-Control"] !== undefined,
      })
      errorRate.add(response.status !== 200)

      sleep(1)

      // Test streaming with range request
      response = http.get(`${BASE_URL}/api/stream/${trackId}`, {
        headers: {
          Range: "bytes=0-8191",
        },
      })
      check(response, {
        "range request status is 206 or 200": (r) => r.status === 206 || r.status === 200,
        "range has accept-ranges": (r) => r.headers["Accept-Ranges"] !== undefined,
      })
      errorRate.add(response.status !== 200 && response.status !== 206)

      // Record analytics (non-blocking)
      http.post(
        `${BASE_URL}/api/analytics/track`,
        JSON.stringify({
          trackId: trackId,
          durationMs: 3000,
        }),
        {
          headers: { "Content-Type": "application/json" },
        },
      )
    }
  }

  sleep(2)
}
