import { describe, expect, it, vi } from "vitest";
import {
  EDIT_REFUSAL_MESSAGE,
  GuruServices,
  normalizeEmail,
} from "./guru.service";
import {
  AllowlistAddSchema,
  CreateTicketSchema,
  ListAuditSchema,
  ListTicketsSchema,
} from "./guru.schema";
import type { TGuruRepository } from "./guru.repository";
import type { GuruTicket } from "@/internal/datastore/guru.types";

// Controller tests mock the repository module so no real DB is touched.
vi.mock("./guru.repository", async (importOriginal) => {
  const actual = await importOriginal<object>();
  return { ...actual, GuruRepository: vi.fn() };
});
import { GuruRepository } from "./guru.repository";
import {
  getMyTicketHandler,
  listMyTicketsHandler,
} from "@/controllers/admin/guru/guru.controller";

// ---------- helpers ----------

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: [],
    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> = {}) =>
  ({
    insertTicket: vi.fn(async (v) => ticket(v as Partial<GuruTicket>)),
    insertAudit: vi.fn(async () => undefined),
    listTicketsByMemberRef: vi.fn(async () => []),
    isAllowlisted: vi.fn(async () => true),
    addToAllowlist: vi.fn(async (email: string, added_by: string) => ({
      id: "al1",
      email,
      added_by,
      created_at: new Date(),
    })),
    removeFromAllowlist: vi.fn(async () => true),
    listTickets: vi.fn(async () => ({ tickets: [], total: 0 })),
    getTicketByReference: vi.fn(async () => undefined),
    listActionsForTicket: vi.fn(async () => []),
    ...over,
  }) as unknown as TGuruRepository;

/** Thin fake Hono Context — just what the handlers touch. */
const fakeContext = (opts: {
  userId: string;
  email?: string;
  body?: unknown;
  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 () => {
        if (opts.body === undefined) throw new Error("no body");
        return opts.body;
      },
      param: (k: string) => opts.params?.[k],
    },
    json: (body: unknown, status = 200) => ({ body, status }),
  } as never;
};

// ---------- normalizeEmail ----------

describe("normalizeEmail", () => {
  it("trims and lowercases", () => {
    expect(normalizeEmail("  Jane.Doe@Karma.COM  ")).toBe("jane.doe@karma.com");
  });
});

// ---------- schemas ----------

describe("AllowlistAddSchema", () => {
  it("rejects non-emails", () => {
    expect(AllowlistAddSchema.safeParse({ email: "not-an-email" }).success).toBe(
      false,
    );
    expect(AllowlistAddSchema.safeParse({}).success).toBe(false);
  });

  it("normalizes case and whitespace", () => {
    const parsed = AllowlistAddSchema.parse({ email: " Jane@Karma.COM " });
    expect(parsed.email).toBe("jane@karma.com");
  });
});

describe("CreateTicketSchema", () => {
  it("turns empty strings into undefined", () => {
    const parsed = CreateTicketSchema.parse({
      member_ref: "",
      category: "  ",
      summary: "",
    });
    expect(parsed.member_ref).toBeUndefined();
    expect(parsed.category).toBeUndefined();
    expect(parsed.summary).toBeUndefined();
  });

  it("rejects an over-long summary", () => {
    expect(
      CreateTicketSchema.safeParse({ summary: "x".repeat(2001) }).success,
    ).toBe(false);
  });

  it("accepts an empty body", () => {
    expect(CreateTicketSchema.safeParse({}).success).toBe(true);
  });
});

describe("ListTicketsSchema", () => {
  it("defaults page and limit", () => {
    const parsed = ListTicketsSchema.parse({});
    expect(parsed.page).toBe(1);
    expect(parsed.limit).toBe(25);
  });

  it("rejects unknown statuses and limit over 100", () => {
    expect(ListTicketsSchema.safeParse({ statuses: ["BOGUS"] }).success).toBe(
      false,
    );
    expect(ListTicketsSchema.safeParse({ limit: 101 }).success).toBe(false);
  });
});

describe("ListAuditSchema", () => {
  it("rejects a non-uuid ticket_id and defaults paging", () => {
    expect(ListAuditSchema.safeParse({ ticket_id: "nope" }).success).toBe(false);
    const parsed = ListAuditSchema.parse({});
    expect(parsed.page).toBe(1);
    expect(parsed.limit).toBe(50);
  });
});

// ---------- services ----------

describe("GuruServices.createTicket", () => {
  it("redacts the summary and audits with the actor email", async () => {
    const repo = mockRepo();
    const services = GuruServices({ GuruRepository: repo });
    await services.createTicket(
      { summary: "member mail is a@b.com please" } as never,
      { id: "user-1", email: " Jane@Karma.COM " },
    );

    const insert = (repo.insertTicket as ReturnType<typeof vi.fn>).mock
      .calls[0][0];
    expect(insert.summary).toContain("[email redacted]");
    expect(insert.summary).not.toContain("a@b.com");
    expect(insert.console_user_id).toBe("user-1");
    expect(insert.concierge_email).toBe("jane@karma.com");

    const audit = (repo.insertAudit as ReturnType<typeof vi.fn>).mock
      .calls[0][0];
    expect(audit.action).toBe("ticket.created");
    expect(audit.actor_email).toBe(" Jane@Karma.COM ");
    expect(audit.ticket_id).toBe("t1");
  });
});

describe("GuruServices.canEdit", () => {
  it("checks the allowlist with the normalized email and returns its boolean", async () => {
    const repo = mockRepo({
      isAllowlisted: vi.fn(async () => false),
    } as never);
    const services = GuruServices({ GuruRepository: repo });
    expect(await services.canEdit("  Jane@Karma.COM ")).toBe(false);
    expect(repo.isAllowlisted).toHaveBeenCalledWith("jane@karma.com");
  });
});

describe("GuruServices allowlist", () => {
  it("addToAllowlist normalizes the email and audits on insert", async () => {
    const repo = mockRepo();
    const services = GuruServices({ GuruRepository: repo });
    const entry = await services.addToAllowlist(
      " New@Karma.COM ",
      "admin@karma.com",
    );
    expect(repo.addToAllowlist).toHaveBeenCalledWith(
      "new@karma.com",
      "admin@karma.com",
    );
    expect(entry).not.toBeNull();
    expect(repo.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({
        action: "allowlist.added",
        actor_email: "admin@karma.com",
        metadata: { email: "new@karma.com" },
      }),
    );
  });

  it("addToAllowlist does not audit a duplicate", async () => {
    const repo = mockRepo({
      addToAllowlist: vi.fn(async () => undefined),
    } as never);
    const services = GuruServices({ GuruRepository: repo });
    const entry = await services.addToAllowlist("dup@karma.com", "admin@x.com");
    expect(entry).toBeNull();
    expect(repo.insertAudit).not.toHaveBeenCalled();
  });

  it("removeFromAllowlist audits only when something was removed", async () => {
    const repo = mockRepo({
      removeFromAllowlist: vi.fn(async () => false),
    } as never);
    const services = GuruServices({ GuruRepository: repo });
    expect(await services.removeFromAllowlist("x@karma.com", "a@x.com")).toBe(
      false,
    );
    expect(repo.insertAudit).not.toHaveBeenCalled();

    const repo2 = mockRepo();
    const services2 = GuruServices({ GuruRepository: repo2 });
    expect(
      await services2.removeFromAllowlist(" X@Karma.COM ", "a@x.com"),
    ).toBe(true);
    expect(repo2.removeFromAllowlist).toHaveBeenCalledWith("x@karma.com");
    expect(repo2.insertAudit).toHaveBeenCalledWith(
      expect.objectContaining({ action: "allowlist.removed" }),
    );
  });
});

// ---------- spec wording ----------

describe("EDIT_REFUSAL_MESSAGE", () => {
  it("matches the spec exactly", () => {
    expect(EDIT_REFUSAL_MESSAGE).toBe(
      "Sorry, you don't have permission to update this member's information.",
    );
  });
});

// ---------- controller ownership ----------

describe("ticket visibility", () => {
  it("listMyTicketsHandler always scopes by the session user id", async () => {
    const repo = mockRepo();
    vi.mocked(GuruRepository).mockReturnValue(repo);
    const c = fakeContext({
      userId: "session-user",
      body: { console_user_id: "attacker", page: 1, limit: 10 },
    });
    await listMyTicketsHandler(c);
    expect(repo.listTickets).toHaveBeenCalledWith(
      expect.objectContaining({ console_user_id: "session-user" }),
    );
  });

  it("getMyTicketHandler returns 404 for a ticket owned by someone else", async () => {
    const repo = mockRepo({
      getTicketByReference: vi.fn(async () =>
        ticket({ console_user_id: "someone-else" }),
      ),
    } as never);
    vi.mocked(GuruRepository).mockReturnValue(repo);
    const c = fakeContext({
      userId: "session-user",
      params: { reference: "GURU-1" },
    });
    const res = (await getMyTicketHandler(c)) as unknown as {
      status: number;
      body: { message: string };
    };
    expect(res.status).toBe(404);
    expect(res.body.message).toBe("Ticket not found");
    expect(repo.listActionsForTicket).not.toHaveBeenCalled();
  });

  it("getMyTicketHandler returns the ticket to its owner", async () => {
    const repo = mockRepo({
      getTicketByReference: vi.fn(async () =>
        ticket({ console_user_id: "session-user" }),
      ),
    } as never);
    vi.mocked(GuruRepository).mockReturnValue(repo);
    const c = fakeContext({
      userId: "session-user",
      params: { reference: "GURU-1" },
    });
    const res = (await getMyTicketHandler(c)) as unknown as {
      status: number;
    };
    expect(res.status).toBe(200);
  });
});
