import { beforeEach, describe, expect, it, vi } from "vitest";
import * as crypto from "node:crypto";
import { redactSensitive } from "./kevo.service";
import {
  contentHash,
  KevoPublishServices,
  renderKnowledgeMarkdown,
} from "./kevo-publish.service";
import { verifyElevenLabsSignature } from "@/routes/kevo/kevo-public.route";
import type { KevoKnowledgeEntry } from "@/internal/datastore/kevo.types";

// ---------- PII redaction ----------

describe("redactSensitive", () => {
  it("redacts email addresses", () => {
    expect(redactSensitive("mail me at jane.doe+x@karma.com please")).toBe(
      "mail me at [email redacted] please",
    );
  });

  it("redacts long digit runs with separators", () => {
    expect(redactSensitive("call +62 812-3456 7890 now")).toBe(
      "call [number redacted] now",
    );
  });

  it("keeps short numbers (years, room numbers, prices)", () => {
    const text = "room 1412 in 2026 costs 150";
    expect(redactSensitive(text)).toBe(text);
  });
});

// ---------- webhook signature ----------

describe("verifyElevenLabsSignature", () => {
  const secret = "whsec_test";
  const body = '{"type":"post_call_transcription"}';
  const sign = (t: number) =>
    `t=${t},v0=${crypto
      .createHmac("sha256", secret)
      .update(`${t}.${body}`)
      .digest("hex")}`;

  it("accepts a valid, fresh signature", () => {
    const now = 1_800_000_000;
    expect(verifyElevenLabsSignature(body, sign(now), secret, now)).toBe(true);
  });

  it("rejects a wrong digest", () => {
    const now = 1_800_000_000;
    expect(
      verifyElevenLabsSignature(body, `t=${now},v0=deadbeef`, secret, now),
    ).toBe(false);
  });

  it("rejects a stale timestamp (>30 min)", () => {
    const now = 1_800_000_000;
    const old = now - 31 * 60;
    expect(verifyElevenLabsSignature(body, sign(old), secret, now)).toBe(false);
  });

  it("rejects a tampered body", () => {
    const now = 1_800_000_000;
    expect(
      verifyElevenLabsSignature(body + " ", sign(now), secret, now),
    ).toBe(false);
  });

  it("rejects malformed headers", () => {
    expect(verifyElevenLabsSignature(body, "nonsense", secret)).toBe(false);
    expect(verifyElevenLabsSignature(body, "t=abc,v0=12", secret)).toBe(false);
  });
});

// ---------- knowledge markdown ----------

const entry = (over: Partial<KevoKnowledgeEntry>): KevoKnowledgeEntry =>
  ({
    id: "x",
    flag_id: null,
    entity: "Entity",
    aliases: [],
    property: null,
    category: "correction",
    verified_text: "Text.",
    status: "APPROVED",
    approved_by: null,
    approved_at: null,
    published_at: null,
    version: 1,
    created_at: new Date(),
    updated_at: null,
    ...over,
  }) as KevoKnowledgeEntry;

describe("renderKnowledgeMarkdown", () => {
  const now = new Date("2026-11-12T00:00:00Z");

  it("groups by property with General last, aliases appended", () => {
    const md = renderKnowledgeMarkdown(
      [
        entry({ entity: "Wifi policy", property: null }),
        entry({
          entity: "Karma Beach",
          property: "Karma Kandara (Bali)",
          aliases: ["Karma Beach Bali"],
          verified_text:
            "A private beach club within Karma Kandara. It is an amenity, not a separate property.",
        }),
      ],
      now,
    );
    expect(md).toContain("## Karma Kandara (Bali)");
    expect(md).toContain(
      '- **Karma Beach**: A private beach club within Karma Kandara. It is an amenity, not a separate property. Also known as: "Karma Beach Bali".',
    );
    expect(md.indexOf("## Karma Kandara (Bali)")).toBeLessThan(
      md.indexOf("## General"),
    );
  });

  it("hash is stable for identical content and changes with content", () => {
    const a = renderKnowledgeMarkdown([entry({})], now);
    const b = renderKnowledgeMarkdown([entry({})], now);
    const c = renderKnowledgeMarkdown([entry({ entity: "Other" })], now);
    expect(contentHash(a)).toBe(contentHash(b));
    expect(contentHash(a)).not.toBe(contentHash(c));
  });
});

// ---------- merge-safe agent attach ----------

describe("attachToAgent", () => {
  beforeEach(() => {
    process.env.ELEVENLABS_API_KEY = "test-key";
    process.env.ELEVENLABS_AGENT_ID = "agent_1";
  });

  it("preserves existing knowledge_base entries when attaching", async () => {
    const existing = [
      { type: "file", id: "doc_other", name: "Resort guide", usage_mode: "auto" },
    ];
    const calls: Array<{ url: string; init?: RequestInit }> = [];
    vi.stubGlobal(
      "fetch",
      vi.fn(async (url: string, init?: RequestInit) => {
        calls.push({ url, init });
        if (!init?.method || init.method === "GET") {
          return new Response(
            JSON.stringify({
              conversation_config: {
                agent: { prompt: { knowledge_base: existing } },
              },
            }),
            { status: 200 },
          );
        }
        return new Response("{}", { status: 200 });
      }),
    );

    const services = KevoPublishServices({} as never);
    await services.attachToAgent("doc_kevo");

    const patch = calls.find((c) => c.init?.method === "PATCH");
    expect(patch).toBeDefined();
    const body = JSON.parse(patch!.init!.body as string);
    const kb = body.conversation_config.agent.prompt.knowledge_base;
    expect(kb).toHaveLength(2);
    expect(kb[0]).toEqual(existing[0]); // nothing dropped
    expect(kb[1]).toMatchObject({ id: "doc_kevo", type: "text" });

    vi.unstubAllGlobals();
  });

  it("does not PATCH when the document is already attached", async () => {
    const calls: string[] = [];
    vi.stubGlobal(
      "fetch",
      vi.fn(async (url: string, init?: RequestInit) => {
        calls.push(init?.method ?? "GET");
        return new Response(
          JSON.stringify({
            conversation_config: {
              agent: {
                prompt: {
                  knowledge_base: [
                    { type: "text", id: "doc_kevo", name: "Kevo" },
                  ],
                },
              },
            },
          }),
          { status: 200 },
        );
      }),
    );

    const services = KevoPublishServices({} as never);
    await services.attachToAgent("doc_kevo");
    expect(calls).toEqual(["GET"]);

    vi.unstubAllGlobals();
  });
});
