import { readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { TGuruRepository } from "./guru.repository";
import type { GuruTicket } from "@/internal/datastore/guru.types";

// Lifecycle increment — concierge close + stale sweep + ClickUp closeClickUpTask.
// No real DB, network, ClickUp, or Viewpoint — all mocked (stage-5/7 conventions).

vi.mock("./guru.repository", async (importOriginal) => {
  const actual = await importOriginal<object>();
  return {
    ...actual,
    GuruRepository: vi.fn(),
    GuruRepositoryFromDb: vi.fn(),
  };
});

const clickupMock = vi.hoisted(() => ({
  createClickUpTask: vi.fn(),
  createClickUpTaskComment: vi.fn(),
  getClickUpTaskComments: vi.fn(),
  addClickUpTaskTags: vi.fn(),
  closeClickUpTask: vi.fn(),
}));
vi.mock("@/lib/clickup/client", () => clickupMock);

vi.mock("@/lib/elevenlabs/client", () => ({ elevenLabsRequest: vi.fn() }));

const createAuditLog = vi.hoisted(() => vi.fn());
vi.mock("@karma/viewpoint-sdk/member", () => ({
  ViewpointMember: vi.fn(() => ({ createAuditLog })),
}));

const loggerMock = vi.hoisted(() => ({
  logError: vi.fn(),
  logInfo: vi.fn(),
}));
vi.mock("@/lib/logger", async (importOriginal) => ({
  ...(await importOriginal<object>()),
  ...loggerMock,
}));

import { GuruRepository, GuruRepositoryFromDb } from "./guru.repository";
import {
  closeTicketByConcierge,
  sweepStaleTickets,
} from "./guru-lifecycle.service";
import { closeTicketHandler } from "@/controllers/admin/guru/guru.controller";

// ---------- fixtures (stage-7 conventions) ----------

const ticket = (over: Partial<GuruTicket> = {}): GuruTicket =>
  ({
    id: "t1",
    reference: "GURU-1",
    console_user_id: "user-1",
    concierge_email: "a@karma.com",
    member_ref: null,
    category: null,
    summary: null,
    status: "OPEN",
    resolution: null,
    conversation_ids: ["conv-1"],
    clickup_task_id: null,
    clickup_task_url: null,
    resolved_at: null,
    created_at: new Date(),
    updated_at: null,
    ...over,
  }) as GuruTicket;

const mockRepo = (over: Partial<TGuruRepository> = {}) =>
  ({
    getTicketByReference: vi.fn(async () => undefined),
    listStaleOpenTickets: vi.fn(async () => []),
    updateTicket: vi.fn(async () => undefined),
    insertAudit: vi.fn(async () => undefined),
    listTicketsByMemberRef: vi.fn(async () => []),
    listActionsForTicket: vi.fn(async () => []),
    ...over,
  }) as unknown as TGuruRepository;

const setRepo = (repo: TGuruRepository) => {
  vi.mocked(GuruRepository).mockReturnValue(repo as never);
  return repo;
};

/** Thin fake Hono Context — just what the handlers touch. */
const fakeContext = (opts: {
  userId: string;
  email?: string;
  params?: Record<string, string>;
}) => {
  const vars: Record<string, unknown> = {
    consoleUserId: opts.userId,
    adminEmail: opts.email ?? "a@karma.com",
  };
  return {
    get: (k: string) => vars[k],
    req: {
      json: async () => {
        throw new Error("no body");
      },
      param: (k: string) => opts.params?.[k],
    },
    json: (body: unknown, status = 200) => ({ body, status }),
  } as never;
};

type Res = { status: number; body: { message: string; data: any } };

const ACTOR = "concierge@karma.com";

afterEach(() => {
  vi.unstubAllEnvs();
  vi.clearAllMocks();
});

// ---------- 1. closeClickUpTask (real client, mocked fetch) ----------

describe("closeClickUpTask (ClickUp client)", () => {
  const realClient = async () =>
    vi.importActual<typeof import("@/lib/clickup/client")>(
      "@/lib/clickup/client",
    );

  const fetchMock = vi.fn();

  const listResponse = (statuses: Array<{ status: string; type: string }>) =>
    new Response(JSON.stringify({ statuses }), { status: 200 });

  beforeEach(() => {
    vi.stubEnv("CLICKUP_API_TOKEN", "pk_test");
    vi.stubGlobal("fetch", fetchMock);
  });

  it("PUTs the 'closed'-type status name", async () => {
    fetchMock
      .mockResolvedValueOnce(
        listResponse([
          { status: "to do", type: "open" },
          { status: "Complete", type: "done" },
          { status: "Closed", type: "closed" },
        ]),
      )
      .mockResolvedValueOnce(new Response("", { status: 200 }));
    const { closeClickUpTask } = await realClient();
    await closeClickUpTask("task-1", "guru-list");

    expect(fetchMock.mock.calls[0][0]).toBe(
      "https://api.clickup.com/api/v2/list/guru-list",
    );
    const [url, init] = fetchMock.mock.calls[1];
    expect(url).toBe("https://api.clickup.com/api/v2/task/task-1");
    expect(init.method).toBe("PUT");
    expect(JSON.parse(init.body)).toEqual({ status: "Closed" });
  });

  it("falls back to the 'done'-type status when no 'closed' exists", async () => {
    fetchMock
      .mockResolvedValueOnce(
        listResponse([
          { status: "to do", type: "open" },
          { status: "Complete", type: "done" },
        ]),
      )
      .mockResolvedValueOnce(new Response("", { status: 200 }));
    const { closeClickUpTask } = await realClient();
    await closeClickUpTask("task-1", "guru-list");

    const [, init] = fetchMock.mock.calls[1];
    expect(JSON.parse(init.body)).toEqual({ status: "Complete" });
  });

  it("throws ClickUpApiError(422) when neither closed nor done exists, no PUT", async () => {
    fetchMock.mockResolvedValueOnce(
      listResponse([{ status: "to do", type: "open" }]),
    );
    const { closeClickUpTask, ClickUpApiError } = await realClient();
    await expect(closeClickUpTask("task-1", "guru-list")).rejects.toThrow(
      ClickUpApiError,
    );
    fetchMock.mockResolvedValueOnce(
      listResponse([{ status: "to do", type: "open" }]),
    );
    await expect(
      closeClickUpTask("task-1", "guru-list"),
    ).rejects.toMatchObject({ status: 422 });
    // Only the two GETs happened — the task was never touched.
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });
});

// ---------- 2–5. closeTicketByConcierge ----------

describe("closeTicketByConcierge", () => {
  beforeEach(() => {
    clickupMock.createClickUpTaskComment.mockResolvedValue({ id: "cm-1" });
    clickupMock.closeClickUpTask.mockResolvedValue(undefined);
    createAuditLog.mockResolvedValue({});
  });

  it("happy path: local close, audit, ClickUp comment+close, redacted Viewpoint CLOSED log", async () => {
    vi.stubEnv("GURU_CLICKUP_LIST_ID", "guru-list");
    const repo = mockRepo();
    const t = ticket({ member_ref: "ACC-9", clickup_task_id: "cu-1" });

    await closeTicketByConcierge(repo, t, ACTOR);

    expect(repo.updateTicket).toHaveBeenCalledWith("t1", {
      status: "RESOLVED",
      resolution: "CLOSED_BY_CONCIERGE",
      resolved_at: expect.any(Date),
    });
    expect(repo.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({
        ticket_id: "t1",
        action: "ticket.closed",
        actor_email: ACTOR,
        clickup_task_id: "cu-1",
        success: true,
      }),
    );
    expect(clickupMock.createClickUpTaskComment).toHaveBeenCalledWith(
      "cu-1",
      expect.stringContaining("no longer an issue"),
    );
    expect(clickupMock.closeClickUpTask).toHaveBeenCalledWith(
      "cu-1",
      "guru-list",
    );
    // Viewpoint: CLOSED log, comment redacted — the actor email (fed into
    // the note) must never appear raw.
    expect(createAuditLog).toHaveBeenCalledTimes(1);
    const vpCall = createAuditLog.mock.calls[0][0];
    expect(vpCall.status).toBe("CLOSED");
    expect(vpCall.accountID).toBe("ACC-9");
    expect(vpCall.comment).not.toContain(ACTOR);
    expect(vpCall.comment).toContain("[email redacted]");
  });

  it("skips closeClickUpTask when GURU_CLICKUP_LIST_ID is unset, still comments", async () => {
    // The repo .env may define it — force "unset" (empty is falsy in the guard).
    vi.stubEnv("GURU_CLICKUP_LIST_ID", "");
    const repo = mockRepo();
    await closeTicketByConcierge(
      repo,
      ticket({ clickup_task_id: "cu-1" }),
      ACTOR,
    );
    expect(clickupMock.createClickUpTaskComment).toHaveBeenCalled();
    expect(clickupMock.closeClickUpTask).not.toHaveBeenCalled();
  });

  it("ClickUp comment failure → clickup.close_failed audit, no throw, Viewpoint still attempted", async () => {
    vi.stubEnv("GURU_CLICKUP_LIST_ID", "guru-list");
    clickupMock.createClickUpTaskComment.mockRejectedValue(
      new Error("clickup down"),
    );
    const repo = mockRepo();
    const t = ticket({ member_ref: "ACC-9", clickup_task_id: "cu-1" });

    await expect(closeTicketByConcierge(repo, t, ACTOR)).resolves.toBeUndefined();

    expect(repo.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({
        action: "clickup.close_failed",
        clickup_task_id: "cu-1",
        success: false,
      }),
    );
    expect(clickupMock.closeClickUpTask).not.toHaveBeenCalled();
    expect(createAuditLog).toHaveBeenCalledWith(
      expect.objectContaining({ status: "CLOSED" }),
    );
  });

  it("Viewpoint 4xx on CLOSED → retried as OPEN with fallback audit metadata", async () => {
    createAuditLog
      .mockRejectedValueOnce(
        Object.assign(new Error("unprocessable"), { status: 422 }),
      )
      .mockResolvedValueOnce({});
    const repo = mockRepo();
    await closeTicketByConcierge(repo, ticket({ member_ref: "ACC-9" }), ACTOR);

    expect(createAuditLog).toHaveBeenCalledTimes(2);
    expect(createAuditLog.mock.calls[0][0].status).toBe("CLOSED");
    expect(createAuditLog.mock.calls[1][0].status).toBe("OPEN");
    expect(repo.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({
        action: "viewpoint.logged",
        metadata: expect.objectContaining({
          log_status: "OPEN",
          fallback: expect.any(String),
        }),
      }),
    );
  });

  it("no member_ref → Viewpoint never called", async () => {
    const repo = mockRepo();
    await closeTicketByConcierge(repo, ticket(), ACTOR);
    expect(createAuditLog).not.toHaveBeenCalled();
  });

  it("no clickup_task_id → no ClickUp calls, still closes and audits", async () => {
    vi.stubEnv("GURU_CLICKUP_LIST_ID", "guru-list");
    const repo = mockRepo();
    await closeTicketByConcierge(repo, ticket(), ACTOR);

    expect(clickupMock.createClickUpTaskComment).not.toHaveBeenCalled();
    expect(clickupMock.closeClickUpTask).not.toHaveBeenCalled();
    expect(repo.updateTicket).toHaveBeenCalledWith(
      "t1",
      expect.objectContaining({ status: "RESOLVED" }),
    );
    expect(repo.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({ action: "ticket.closed" }),
    );
  });
});

// ---------- 6. sweepStaleTickets ----------

describe("sweepStaleTickets", () => {
  it("one ticket failing does not stop the sweep; returns the stale count; error logged", async () => {
    const t1 = ticket({ id: "t1", reference: "GURU-1" });
    const t2 = ticket({ id: "t2", reference: "GURU-2" });
    const repo = mockRepo({
      listStaleOpenTickets: vi.fn(async () => [t1, t2]),
      updateTicket: vi
        .fn()
        .mockRejectedValueOnce(new Error("db down"))
        .mockResolvedValue(undefined),
    } as never);
    vi.mocked(GuruRepositoryFromDb).mockReturnValue(repo as never);

    const count = await sweepStaleTickets({} as never);

    expect(count).toBe(2);
    expect(repo.listStaleOpenTickets).toHaveBeenCalledWith(7);
    // First close threw, second still processed fully.
    expect(repo.updateTicket).toHaveBeenCalledTimes(2);
    expect(repo.updateTicket).toHaveBeenLastCalledWith(
      "t2",
      expect.objectContaining({
        status: "RESOLVED",
        resolution: "AUTO_CLOSED_INACTIVE",
      }),
    );
    expect(repo.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({ ticket_id: "t2", action: "ticket.auto_closed" }),
    );
    expect(loggerMock.logError).toHaveBeenCalledWith(
      expect.stringContaining("GURU-1"),
    );
  });
});

// ---------- 7. closeTicketHandler ----------

describe("closeTicketHandler", () => {
  it("returns 404 for a non-owned ticket and closes nothing", async () => {
    const repo = setRepo(
      mockRepo({
        getTicketByReference: vi.fn(async () =>
          ticket({ console_user_id: "someone-else" }),
        ),
      } as never),
    );
    const c = fakeContext({ userId: "user-1", params: { reference: "GURU-1" } });
    const res = (await closeTicketHandler(c)) as unknown as Res;

    expect(res.status).toBe(404);
    expect(res.body.message).toBe("Ticket not found");
    expect(repo.updateTicket).not.toHaveBeenCalled();
    expect(repo.insertAudit).not.toHaveBeenCalled();
  });

  it("returns 409 when the ticket is not OPEN", async () => {
    const repo = setRepo(
      mockRepo({
        getTicketByReference: vi.fn(async () =>
          ticket({ status: "RESOLVED", resolution: "CLOSED_BY_CONCIERGE" }),
        ),
      } as never),
    );
    const c = fakeContext({ userId: "user-1", params: { reference: "GURU-1" } });
    const res = (await closeTicketHandler(c)) as unknown as Res;

    expect(res.status).toBe(409);
    expect(repo.updateTicket).not.toHaveBeenCalled();
  });

  it("owner + OPEN → 200 {closed:true} and the ticket is resolved", async () => {
    const repo = setRepo(
      mockRepo({
        getTicketByReference: vi.fn(async () => ticket()),
      } as never),
    );
    const c = fakeContext({
      userId: "user-1",
      email: ACTOR,
      params: { reference: "GURU-1" },
    });
    const res = (await closeTicketHandler(c)) as unknown as Res;

    expect(res.status).toBe(200);
    expect(res.body.data).toEqual({ closed: true });
    expect(repo.updateTicket).toHaveBeenCalledWith(
      "t1",
      expect.objectContaining({
        status: "RESOLVED",
        resolution: "CLOSED_BY_CONCIERGE",
      }),
    );
    expect(repo.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({ action: "ticket.closed", actor_email: ACTOR }),
    );
  });
});

// ---------- 8. route wiring ----------

describe("POST /tickets/:reference/close route guard", () => {
  it("registers the close route behind withConsoleUserRole('guru','update')", () => {
    const src = readFileSync(
      join(__dirname, "../../routes/guru/guru-admin.route.ts"),
      "utf8",
    );
    expect(src).toMatch(
      /GuruAdminRoutes\.post\(\s*"\/tickets\/:reference\/close",\s*withConsoleUserRole\("guru",\s*"update"\),\s*closeTicketHandler,\s*\)/,
    );
    expect(src.match(/"\/tickets\/:reference\/close"/g)).toHaveLength(1);
  });
});
