import { describe, expect, it } from "vitest";
import {
  checkPassword,
  createSession,
  verifySession,
} from "../../src/auth.js";
import { T0 } from "../helpers.js";

const SECRET = "test-secret-long-enough";

describe("auth (TC-FR-AUTH-002)", () => {
  it("正パスワードは一致、誤りは不一致（定数時間）", () => {
    expect(checkPassword("abc", "abc")).toBe(true);
    expect(checkPassword("abc", "abd")).toBe(false);
    expect(checkPassword("abc", "")).toBe(false);
  });

  it("有効なセッションは検証成功、未失効", async () => {
    const token = await createSession(SECRET, T0);
    expect(await verifySession(SECRET, token, T0 + 1000)).toBe(true);
  });

  it("署名改竄を拒否する", async () => {
    const token = await createSession(SECRET, T0);
    const tampered = token.slice(0, -2) + "xx";
    expect(await verifySession(SECRET, tampered, T0)).toBe(false);
  });

  it("別シークレットでは検証失敗", async () => {
    const token = await createSession(SECRET, T0);
    expect(await verifySession("other-secret", token, T0)).toBe(false);
  });

  it("失効後は検証失敗", async () => {
    const token = await createSession(SECRET, T0, 1000);
    expect(await verifySession(SECRET, token, T0 + 2000)).toBe(false);
  });

  it("空/不正形式は失敗", async () => {
    expect(await verifySession(SECRET, undefined, T0)).toBe(false);
    expect(await verifySession(SECRET, "garbage", T0)).toBe(false);
  });
});
