import { describe, expect, test } from "bun:test";

import type { StoredCheckResult } from "../../src/server/checker/types";

import { createApiError, createHeaders, formatDuration, jsonResponse, mapCheckResult } from "../../src/server/helpers";

describe("createApiError", () => {
  test("创建错误响应对象", () => {
    const result = createApiError("Not found", 404);
    expect(result).toEqual({ error: "Not found", status: 404 });
  });

  test("支持不同的错误消息和状态码", () => {
    const badRequest = createApiError("Bad request", 400);
    const internalError = createApiError("Internal error", 500);

    expect(badRequest).toEqual({ error: "Bad request", status: 400 });
    expect(internalError).toEqual({ error: "Internal error", status: 500 });
  });
});

describe("createHeaders", () => {
  test("生产模式添加安全 headers", () => {
    const headers = createHeaders("production", { "Content-Type": "application/json" });

    expect(headers.get("X-Content-Type-Options")).toBe("nosniff");
    expect(headers.get("Referrer-Policy")).toBe("strict-origin-when-cross-origin");
    expect(headers.get("Content-Type")).toBe("application/json");
  });

  test("非生产模式不添加安全 headers", () => {
    const headers = createHeaders("test", { "Content-Type": "application/json" });

    expect(headers.get("X-Content-Type-Options")).toBeNull();
    expect(headers.get("Referrer-Policy")).toBeNull();
    expect(headers.get("Content-Type")).toBe("application/json");
  });

  test("保留传入的自定义 headers", () => {
    const headers = createHeaders("production", { "X-Custom-Header": "custom-value" });

    expect(headers.get("X-Custom-Header")).toBe("custom-value");
  });
});

describe("jsonResponse", () => {
  test("创建 JSON 响应", () => {
    const body = { message: "Hello" };
    const response = jsonResponse(body, { mode: "test" });

    expect(response.status).toBe(200);
    expect(response.headers.get("Content-Type")).toBe("application/json; charset=utf-8");
  });

  test("生产模式响应包含安全 headers", () => {
    const response = jsonResponse({ data: "test" }, { mode: "production" });

    expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff");
    expect(response.headers.get("Referrer-Policy")).toBe("strict-origin-when-cross-origin");
  });

  test("支持自定义状态码", () => {
    const response = jsonResponse({ error: "Not found" }, { mode: "test", status: 404 });

    expect(response.status).toBe(404);
  });

  test("支持自定义 headers", () => {
    const response = jsonResponse(
      { data: "test" },
      {
        headers: { "X-Custom": "value" },
        mode: "test",
      },
    );

    expect(response.headers.get("X-Custom")).toBe("value");
  });

  test("响应 body 可以被解析为 JSON", async () => {
    const body = { count: 42, message: "Hello" };
    const response = jsonResponse(body, { mode: "test" });

    const parsed = (await response.json()) as { count: number; message: string };
    expect(parsed).toEqual(body);
  });
});

describe("formatDuration", () => {
  test("毫秒格式化", () => {
    expect(formatDuration(100)).toBe("100ms");
    expect(formatDuration(999)).toBe("999ms");
  });

  test("秒格式化（整秒）", () => {
    expect(formatDuration(1000)).toBe("1s");
    expect(formatDuration(5000)).toBe("5s");
    expect(formatDuration(59000)).toBe("59s");
  });

  test("分钟格式化（整分钟）", () => {
    expect(formatDuration(60000)).toBe("1m");
    expect(formatDuration(120000)).toBe("2m");
    expect(formatDuration(300000)).toBe("5m");
  });

  test("非整秒/整分钟保持毫秒", () => {
    expect(formatDuration(1500)).toBe("1500ms");
    expect(formatDuration(61123)).toBe("61123ms");
  });
});

function makeRow(overrides: Partial<StoredCheckResult> = {}): StoredCheckResult {
  return {
    duration_ms: 12,
    failure: null,
    id: 1,
    matched: 1,
    observation: null,
    target_id: "target-1",
    timestamp: "2025-01-01T00:00:00.000Z",
    ...overrides,
  };
}

describe("mapCheckResult", () => {
  test("反序列化 observation 并构造 detail", () => {
    const result = mapCheckResult(makeRow({ observation: JSON.stringify({ statusCode: 200 }) }), "http");
    expect(result.detail).toBe("HTTP 200");
    expect(result.observation).toEqual({ statusCode: 200 });
  });

  test("null observation 返回 null detail", () => {
    const result = mapCheckResult(makeRow(), "http");
    expect(result.detail).toBeNull();
    expect(result.observation).toBeNull();
  });

  test("未知 type 不影响响应序列化", () => {
    const result = mapCheckResult(makeRow({ observation: JSON.stringify({ statusCode: 200 }) }), "unknown");
    expect(result.detail).toBeNull();
    expect(result.observation).toEqual({ statusCode: 200 });
  });

  test("损坏 observation JSON 返回 null observation", () => {
    const result = mapCheckResult(makeRow({ observation: "{invalid json" }), "http");
    expect(result.detail).toBeNull();
    expect(result.observation).toBeNull();
  });
});
