import { describe, test, assert } from "vitest";
import { parseLog } from "../utils/alloy-log-parser";
import { readFile } from "node:fs/promises";
import { join } from "node:path";

describe("instrumentation integration test", () => {
  test("should exclude health url and process only dummy calls", async () => {
    const data = await readFile(join(__dirname, "logs.txt"), "utf-8");

    let health_traces_counter = 0;
    let dummy_traces_counter = 0;

    for (const line of data.split(/\nts=/)) {
      const parsedLine: Record<string, object | string | number> =
        parseLog(line);

      if (
        parsedLine["attributes"] &&
        parsedLine["attributes"]["span_kind"] &&
        parsedLine["attributes"]["span_kind"] === "trace"
      ) {
        if (parsedLine["attributes"]["http.target"] === "/api/dummy") {
          dummy_traces_counter++;

          // verify global sdk span resource
          assert.equal(
            parsedLine["resource_attributes"]["team.infra.pod"],
            "01",
          );
          assert.equal(
            parsedLine["resource_attributes"]["team.service.type"],
            "fastify",
          );

          // verify global sdk span attributes
          assert.equal(parsedLine["attributes"]["signal.namespace"], "example");

          // verify runtime custom span inside dev application
          assert.equal(parsedLine["attributes"]["business.info"], "dummy");
          assert.equal(
            parsedLine["attributes"]["business.request_type"],
            "application/json",
          );

          continue;
        }
        if (parsedLine["attributes"]["http.target"] === "/api/health") {
          health_traces_counter++;
        }
      }
    }

    assert.equal(health_traces_counter, 0);
    assert.equal(dummy_traces_counter, 2);
  });
});
