import request from "supertest";
import app from "../../src/app.js";
import { setupTestDb, cleanUpTestDb } from "../helpers/dbSetup.js";

describe("Performance & Latency Benchmarks", () => {
  beforeAll(async () => {
    await setupTestDb();
  });

  afterAll(async () => {
    await cleanUpTestDb();
  });

  it("should respond to GET / (Health Check) in less than 50ms", async () => {
    const start = performance.now();
    const res = await request(app).get("/");
    const duration = performance.now() - start;

    expect(res.status).toBe(200);
    expect(res.body.status).toBe("Airpero SaaS Operational");
    console.log(`⏱  GET / (Health Check) Latency: ${duration.toFixed(2)}ms`);
    expect(duration).toBeLessThan(50);
  });

  it("should run 20 consecutive requests to GET / and verify average latency is under 20ms", async () => {
    const iterations = 20;
    let totalDuration = 0;
    const agent = request.agent(app);

    for (let i = 0; i < iterations; i++) {
      const start = performance.now();
      await agent.get("/");
      totalDuration += performance.now() - start;
    }

    const averageLatency = totalDuration / iterations;
    console.log(`⏱  Average latency over ${iterations} requests: ${averageLatency.toFixed(2)}ms`);
    expect(averageLatency).toBeLessThan(20);
  });

  it("should return a 401 Unauthorized for route verification in less than 80ms", async () => {
    // Testing protected customer routes to verify middleware check latency
    const start = performance.now();
    const res = await request(app).get("/api/v1/merchants/me");
    const duration = performance.now() - start;

    expect(res.status).toBe(401);
    console.log(`⏱  Protected Route Auth Deny Latency: ${duration.toFixed(2)}ms`);
    expect(duration).toBeLessThan(80);
  });
});
