/**
 * Unit tests for logger: level filtering and console delegation.
 * Ported from webapp/js/logger.test.js.
 */

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { logger } from "./logger";

describe("logger", () => {
  beforeEach(() => {
    vi.spyOn(console, "debug").mockImplementation(() => {});
    vi.spyOn(console, "info").mockImplementation(() => {});
    vi.spyOn(console, "warn").mockImplementation(() => {});
    vi.spyOn(console, "error").mockImplementation(() => {});
  });

  afterEach(() => {
    vi.restoreAllMocks();
    if (globalThis.window) {
      delete (globalThis.window as unknown as { __DT_LOG_LEVEL?: string }).__DT_LOG_LEVEL;
    }
  });

  function setLevel(level: string) {
    if (!globalThis.window) (globalThis as unknown as { window: object }).window = {};
    (globalThis.window as unknown as { __DT_LOG_LEVEL?: string }).__DT_LOG_LEVEL = level;
  }

  it("at level info does not call console.debug", () => {
    setLevel("info");
    logger.debug("test");
    expect(console.debug).not.toHaveBeenCalled();
  });

  it("at level info calls console.info for logger.info", () => {
    setLevel("info");
    logger.info("hello");
    expect(console.info).toHaveBeenCalledWith("[DutyTeller][info]", "hello");
  });

  it("at level info calls console.warn and console.error", () => {
    setLevel("info");
    logger.warn("w");
    logger.error("e");
    expect(console.warn).toHaveBeenCalledWith("[DutyTeller][warn]", "w");
    expect(console.error).toHaveBeenCalledWith("[DutyTeller][error]", "e");
  });

  it("at level debug calls console.debug", () => {
    setLevel("debug");
    logger.debug("dbg");
    expect(console.debug).toHaveBeenCalledWith("[DutyTeller][debug]", "dbg");
  });

  it("at level error does not call console.debug or console.info", () => {
    setLevel("error");
    logger.debug("d");
    logger.info("i");
    expect(console.debug).not.toHaveBeenCalled();
    expect(console.info).not.toHaveBeenCalled();
  });

  it("at level error calls console.error", () => {
    setLevel("error");
    logger.error("err");
    expect(console.error).toHaveBeenCalledWith("[DutyTeller][error]", "err");
  });

  it("passes extra args to console", () => {
    setLevel("info");
    logger.info("msg", { foo: 1 }, "bar");
    expect(console.info).toHaveBeenCalledWith(
      "[DutyTeller][info]",
      "msg",
      { foo: 1 },
      "bar"
    );
  });

  it("defaults to info when __DT_LOG_LEVEL is missing", () => {
    if (globalThis.window) delete (globalThis.window as unknown as { __DT_LOG_LEVEL?: string }).__DT_LOG_LEVEL;
    logger.debug("no");
    expect(console.debug).not.toHaveBeenCalled();
    logger.info("yes");
    expect(console.info).toHaveBeenCalledWith("[DutyTeller][info]", "yes");
  });

  it("defaults to info when __DT_LOG_LEVEL is invalid", () => {
    setLevel("invalid");
    logger.debug("no");
    expect(console.debug).not.toHaveBeenCalled();
  });
});
