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

const errorRate = new Rate("errors")

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

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

export default function () {
  // Test tracks API
  let response = http.get(`${BASE_URL}/api/tracks`)
  check(response, {
    "tracks status is 200": (r) => r.status === 200,
    "tracks response is JSON": (r) => r.headers["Content-Type"]?.includes("application/json"),
    "tracks has success field": (r) => JSON.parse(r.body).success !== undefined,
  })
  errorRate.add(response.status !== 200)

  sleep(1)

  // Test genres API
  response = http.get(`${BASE_URL}/api/genres`)
  check(response, {
    "genres status is 200": (r) => r.status === 200,
    "genres response is JSON": (r) => r.headers["Content-Type"]?.includes("application/json"),
  })
  errorRate.add(response.status !== 200)

  sleep(1)

  // Test analytics API
  response = http.get(`${BASE_URL}/api/analytics/track?period=7d`)
  check(response, {
    "analytics status is 200": (r) => r.status === 200,
    "analytics response is JSON": (r) => r.headers["Content-Type"]?.includes("application/json"),
  })
  errorRate.add(response.status !== 200)

  sleep(2)
}
