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

/**
 * Tests for the tool-build handover tools (entitlements, availability,
 * submission log, external booking status, email delivery). Same conventions
 * as guru-stage3.test.ts: no real DB/Viewpoint/Redis, everything mocked.
 */

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

const vpAccount = vi.hoisted(() => vi.fn());
vi.mock("@/internal/viewpoint/member", async (importOriginal) => ({
  ...(await importOriginal<object>()),
  getViewPointAccountById: vpAccount,
}));

const vpPoints = vi.hoisted(() => vi.fn());
vi.mock("@/viewpoint", async (importOriginal) => ({
  ...(await importOriginal<object>()),
  getMemberPoints: vpPoints,
}));

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

const vpUnits = vi.hoisted(() => vi.fn());
vi.mock("@karma/viewpoint-sdk/destination", () => ({
  ViewpointDestination: vi.fn(() => ({ findDestinationUnit: vpUnits })),
}));

const hotDeals = vi.hoisted(() => vi.fn(() => ({}) as Record<string, unknown>));
vi.mock("@/controllers/admin/availability/availability.controller", () => ({
  loadHotDeals: hotDeals,
}));

const membersMock = vi.hoisted(() => ({
  GetMembersByMembershipNumber: vi.fn(),
}));
vi.mock("@/internal/members/member.services", () => ({
  MemberServices: vi.fn(() => membersMock),
}));

const findBooking = vi.hoisted(() => vi.fn());
const listBookings = vi.hoisted(() => vi.fn());
vi.mock("@/internal/viewpoint-db/signup-bookings.repo", async (importOriginal) => ({
  ...(await importOriginal<object>()),
  findBookingByNumber: findBooking,
  listBookingsForMemberships: listBookings,
}));
vi.mock("@/internal/viewpoint-db/kcgm-bookings.repo", async (importOriginal) => ({
  ...(await importOriginal<object>()),
  getViewpointDB: vi.fn(() => ({})),
}));

import { GuruRepository } from "./guru.repository";
import {
  getAvailability,
  getExternalBookingStatus,
  getSubmissionLog,
} from "./guru-tools.service";
import { GuruPublicRoutes } from "@/routes/guru/guru-public.route";

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> = {}) =>
  ({
    insertAudit: vi.fn(async () => undefined),
    listTicketsByMemberRef: vi.fn(async () => []),
    getTicketByConversation: vi.fn(async () => ticket()),
    updateTicket: vi.fn(async () => undefined),
    ...over,
  }) as unknown as TGuruRepository;

const SECRET = "guru-secret-test";

const post = (path: string, body: unknown) =>
  GuruPublicRoutes.request(path, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-guru-secret": SECRET,
    },
    body: JSON.stringify(body),
  });

beforeEach(() => {
  vi.stubEnv("GURU_TOOL_SHARED_SECRET", SECRET);
  vi.mocked(GuruRepository).mockReturnValue(mockRepo());
});

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

// ---------- guru_entitlements ----------

const CONTRACT = {
  ContractID: 159027,
  AccountID: "905167",
  ExternalContractID: "RGCID932/110122/1020MR",
  Quantity: 210,
  InventoryType: "POINTS",
  UnitTypeDesc: null,
  WeekTypeDesc: "RED",
  PurchaseDate: "2022-01-11T00:00:00",
  PaidDate: "2022-09-30T00:00:00",
  ExpiryDate: "2042-12-31T00:00:00",
  ResortName: "Karma Club Indonesia",
  Term: 20,
  CommenceDate: "2023-01-01T00:00:00",
  // Must never reach the agent: card numbers / prices live in here.
  CRMData: [
    { FieldName: "Comment 1", Value: "5426-4009-1101-9822" },
    { FieldName: "Total Purchase Price", Value: "65000000" },
  ],
  AccountManager: "vp107",
};

const POINTS_LINE = {
  PointsEntitlementID: 1,
  PointsClubName: "Karma Club Indonesia",
  PointsType: "LEVIED",
  Status: "ACTIVE",
  EntitlementYear: 2027,
  Issued: 210,
  Balance: 210,
  ExpiryDate: "2029-12-31T00:00:00",
};

describe("guru_entitlements", () => {
  it("returns whitelisted contracts + all-club entitlement lines", async () => {
    vpAccount.mockResolvedValue({
      AccountType: "Owner",
      AccountStatus: "Active",
      ServiceCenter: "Bali",
    });
    vpContracts.mockResolvedValue([CONTRACT]);
    vpPoints.mockResolvedValue([POINTS_LINE]);

    const res = await post("/tools/entitlements", {
      conversation_id: "conv-1",
      membership_number: "905167",
    });
    expect(res.status).toBe(200);
    const body = (await res.json()) as { status: string; data: any };
    expect(body.status).toBe("ok");
    expect(body.data.account).toMatchObject({
      account_type: "Owner",
      account_status: "Active",
    });
    expect(body.data.contracts[0]).toMatchObject({
      inventory_type: "POINTS",
      resort: "Karma Club Indonesia",
      fee_paid: true,
      expired: false,
    });
    expect(body.data.entitlements[0]).toMatchObject({
      club: "Karma Club Indonesia",
      type: "LEVIED",
      status: "ACTIVE",
      balance: 210,
    });
    // Authoritative all-clubs call, surfaced for auditability.
    expect(body.data.club_resort_id_used).toBe(0);
    expect(vpPoints).toHaveBeenCalledWith("905167", 0);
  });

  it("never leaks CRMData (card numbers, prices) or account manager", async () => {
    vpAccount.mockResolvedValue(null);
    vpContracts.mockResolvedValue([CONTRACT]);
    vpPoints.mockResolvedValue([]);

    const res = await post("/tools/entitlements", {
      conversation_id: "conv-1",
      membership_number: "905167",
    });
    const text = await res.text();
    expect(text).not.toContain("5426-4009-1101-9822");
    expect(text).not.toContain("65000000");
    expect(text).not.toContain("CRMData");
    expect(text).not.toContain("vp107");
  });

  it("flags an expired contract and unpaid fees", async () => {
    vpAccount.mockResolvedValue(null);
    vpContracts.mockResolvedValue([
      { ...CONTRACT, ExpiryDate: "2020-12-31T00:00:00", PaidDate: null },
    ]);
    vpPoints.mockResolvedValue([]);

    const res = await post("/tools/entitlements", {
      conversation_id: "conv-1",
      membership_number: "905167",
    });
    const body = (await res.json()) as { data: any };
    expect(body.data.contracts[0]).toMatchObject({
      expired: true,
      fee_paid: false,
    });
  });

  it("returns not_found when nothing exists for the member", async () => {
    vpAccount.mockResolvedValue(null);
    vpContracts.mockResolvedValue([]);
    vpPoints.mockResolvedValue([]);

    const res = await post("/tools/entitlements", {
      conversation_id: "conv-1",
      membership_number: "000000",
    });
    expect(res.status).toBe(200);
    expect(await res.json()).toMatchObject({ status: "not_found" });
  });

  it("returns an upstream error when every Viewpoint call fails", async () => {
    vpAccount.mockRejectedValue(new Error("vp down"));
    vpContracts.mockRejectedValue(new Error("vp down"));
    vpPoints.mockRejectedValue(new Error("vp down"));

    const res = await post("/tools/entitlements", {
      conversation_id: "conv-1",
      membership_number: "905167",
    });
    expect(res.status).toBe(500);
    const body = (await res.json()) as { status: string; message: string };
    expect(body.status).toBe("error");
    expect(body.message).toContain("Viewpoint");
  });

  it("still answers from points when contracts fail (partial upstream)", async () => {
    vpAccount.mockResolvedValue(null);
    vpContracts.mockRejectedValue(new Error("vp down"));
    vpPoints.mockResolvedValue([POINTS_LINE]);

    const res = await post("/tools/entitlements", {
      conversation_id: "conv-1",
      membership_number: "905167",
    });
    expect(res.status).toBe(200);
    const body = (await res.json()) as { status: string; data: any };
    expect(body.status).toBe("ok");
    expect(body.data.entitlements).toHaveLength(1);
  });

  it("rejects a call without a bound ticket (permission boundary)", async () => {
    vi.mocked(GuruRepository).mockReturnValue(
      mockRepo({ getTicketByConversation: vi.fn(async () => undefined) } as never),
    );
    const res = await post("/tools/entitlements", {
      conversation_id: "conv-x",
      membership_number: "905167",
    });
    expect(res.status).toBe(403);
  });
});

// ---------- guru_availability ----------

/** Minimal kysely stub: selectFrom("resorts")...executeTakeFirst() → row. */
const ctxWithResort = (row: unknown) =>
  ({
    get: () => ({
      selectFrom: () => ({
        where: () => ({
          select: () => ({ executeTakeFirst: async () => row }),
        }),
      }),
    }),
  }) as never;

const RESORT = {
  name: "Karma Royal Palms",
  is_active: true,
  blackout_periods: [],
  open_close_periods: [],
};

const unitDays = (count: number, dates: string[]) => ({
  UnitCategoryID: 1,
  UnitCategory: "1 Bedroom Apartment",
  UnitCategoryCode: "T1",
  Days: dates.map((Date_) => ({ Date: Date_, UnitCount: count, Rates: [] })),
});

describe("guru_availability", () => {
  beforeEach(() => {
    hotDeals.mockReturnValue({});
    vpUnits.mockResolvedValue([]);
  });

  it("rejects bad or inverted dates", async () => {
    const bad = await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "01-12-2026",
      departure: "2026-12-05",
    });
    expect(bad).toMatchObject({ status: "error" });
    const inverted = await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "2026-12-05",
      departure: "2026-12-01",
    });
    expect(inverted).toMatchObject({ status: "error" });
  });

  it("returns not_found for an unknown resort code", async () => {
    const r = await getAvailability(ctxWithResort(undefined), {
      resort_code: "nope",
      arrival: "2026-12-01",
      departure: "2026-12-05",
    });
    expect(r).toMatchObject({ status: "not_found" });
  });

  it("available when inventory exists every night and no rule blocks", async () => {
    vpUnits.mockResolvedValue([
      unitDays(3, ["2026-12-01", "2026-12-02", "2026-12-03", "2026-12-04"]),
    ]);
    const r = (await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "2026-12-01",
      departure: "2026-12-05",
    })) as { status: string; data: any };
    expect(r.status).toBe("ok");
    expect(r.data.available).toBe(true);
    expect(r.data.blocked_by).toEqual([]);
    expect(r.data.units[0]).toMatchObject({
      unit_code: "T1",
      available_every_night: true,
      min_units_free: 3,
    });
  });

  it("names the blackout rule that blocks the stay", async () => {
    const r = (await getAvailability(
      ctxWithResort({
        ...RESORT,
        blackout_periods: [
          { label: "Christmas blackout", start_date: "2026-12-20", end_date: "2027-01-05" },
        ],
      }),
      { resort_code: "13", arrival: "2026-12-24", departure: "2026-12-28" },
    )) as { data: any };
    expect(r.data.available).toBe(false);
    expect(r.data.blocked_by).toEqual([
      { rule: "blackout", detail: "Christmas blackout" },
    ]);
  });

  it("catches a recurring annual closure across the year wrap", async () => {
    const r = (await getAvailability(
      ctxWithResort({
        ...RESORT,
        open_close_periods: [
          {
            period_type: "RECURRING_ANNUAL",
            label: "Monsoon closure",
            start_month_day: "11-15",
            end_month_day: "01-15",
          },
        ],
      }),
      { resort_code: "13", arrival: "2027-01-02", departure: "2027-01-06" },
    )) as { data: any };
    expect(r.data.blocked_by).toEqual([
      { rule: "resort_closure", detail: "Monsoon closure" },
    ]);
  });

  it("flags arrivals beyond the two-year booking horizon", async () => {
    const r = (await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "2031-01-01",
      departure: "2031-01-05",
    })) as { data: any };
    expect(r.data.blocked_by[0].rule).toBe("booking_horizon");
  });

  it("reports sold-out nights and no_inventory", async () => {
    vpUnits.mockResolvedValue([
      {
        ...unitDays(0, ["2026-12-01", "2026-12-02"]),
      },
    ]);
    const withUnits = (await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "2026-12-01",
      departure: "2026-12-03",
    })) as { data: any };
    expect(withUnits.data.units[0].sold_out_nights).toEqual([
      "2026-12-01",
      "2026-12-02",
    ]);
    expect(withUnits.data.available).toBe(false);

    vpUnits.mockResolvedValue([]);
    const empty = (await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "2026-12-01",
      departure: "2026-12-03",
    })) as { data: any };
    expect(empty.data.blocked_by[0].rule).toBe("no_inventory");
  });

  it("filters by unit_code case-insensitively", async () => {
    vpUnits.mockResolvedValue([
      unitDays(2, ["2026-12-01"]),
      { ...unitDays(5, ["2026-12-01"]), UnitCategoryCode: "T2I" },
    ]);
    const r = (await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "2026-12-01",
      departure: "2026-12-02",
      unit_code: "t1",
    })) as { data: any };
    expect(r.data.units).toHaveLength(1);
    expect(r.data.units[0].unit_code).toBe("T1");
  });

  it("lists active hot deals with window coverage and tier restriction", async () => {
    hotDeals.mockReturnValue({
      deal_x: {
        resort: "Karma Royal Palms",
        starts: "2026-01-01",
        expires: "2027-12-31",
        travel_between: [["2026-12-01", "2027-01-31"]],
        unit_code: ["T1"],
        roles: ["contract_kcde_nindia"],
      },
      other_resort_deal: { resort: "Karma Bavaria", travel_between: [] },
      expired_deal: {
        resort: "Karma Royal Palms",
        starts: "2020-01-01",
        expires: "2020-12-31",
      },
    });
    vpUnits.mockResolvedValue([unitDays(1, ["2026-12-01"])]);
    const r = (await getAvailability(ctxWithResort(RESORT), {
      resort_code: "13",
      arrival: "2026-12-01",
      departure: "2026-12-02",
    })) as { data: any };
    expect(r.data.hot_deals_at_resort).toEqual([
      expect.objectContaining({
        hot_deal_id: "deal_x",
        covers_these_dates: true,
        tier_restricted: true,
      }),
    ]);
  });

  it("still reports rules when the Viewpoint inventory call fails", async () => {
    vpUnits.mockRejectedValue(new Error("vp down"));
    const r = (await getAvailability(
      ctxWithResort({
        ...RESORT,
        blackout_periods: [
          { start_date: "2026-12-01", end_date: "2026-12-31" },
        ],
      }),
      { resort_code: "13", arrival: "2026-12-10", departure: "2026-12-12" },
    )) as { status: string; data: any };
    expect(r.status).toBe("ok");
    expect(r.data.blocked_by[0].rule).toBe("blackout");
    expect(r.data.inventory_note).toContain("failed");
  });

  it("over the route: requires resort_code and dates", async () => {
    const res = await post("/tools/availability", { conversation_id: "conv-1" });
    expect(res.status).toBe(400);
  });
});

// ---------- guru_submission_log ----------

/** Chainable kysely stub for booking_requests; where/orderBy/limit no-ops. */
const ctxWithSubmissions = (rows: unknown[]) => {
  const chain: any = {
    where: () => chain,
    select: () => chain,
    orderBy: () => chain,
    limit: () => chain,
    execute: async () => rows,
  };
  return { get: () => ({ selectFrom: () => chain }) } as never;
};

const SUBMISSION = {
  type: "destination_booking",
  status: "ACTIVE",
  ext_booking_id: null as string | null,
  guest_count: 2,
  created_at: new Date("2026-10-01T10:00:00Z"),
  // Columns the DTO must never expose even if selected by mistake:
  email: "jane.doe@karma.com",
  comment: "call me on +62 812 345 678",
};

describe("guru_submission_log", () => {
  beforeEach(() => {
    membersMock.GetMembersByMembershipNumber.mockResolvedValue([
      { member_id: "42485" },
    ]);
  });

  it("maps submissions and flags ones that never became a Viewpoint booking", async () => {
    const r = (await getSubmissionLog(ctxWithSubmissions([SUBMISSION]), {
      membership_number: "KC1",
    })) as { status: string; data: any };
    expect(r.status).toBe("ok");
    expect(r.data.submissions[0]).toMatchObject({
      type: "destination_booking",
      request_status: "ACTIVE",
    });
    expect(r.data.submissions[0].viewpoint_booking.note).toContain(
      "did not create",
    );
    expect(findBooking).not.toHaveBeenCalled();
  });

  it("correlates ext_booking_id with the Viewpoint booking", async () => {
    findBooking.mockResolvedValue({
      booking_no: "VP-9",
      status: "ON HOLD",
      arrival: "2026-12-01",
      departure: "2026-12-05",
    });
    const r = (await getSubmissionLog(
      ctxWithSubmissions([{ ...SUBMISSION, ext_booking_id: "VP-9" }]),
      { membership_number: "KC1" },
    )) as { data: any };
    expect(r.data.submissions[0].viewpoint_booking).toMatchObject({
      booking_no: "VP-9",
      status: "ON HOLD",
    });
  });

  it("reports a referenced booking missing from Viewpoint", async () => {
    findBooking.mockResolvedValue(null);
    const r = (await getSubmissionLog(
      ctxWithSubmissions([{ ...SUBMISSION, ext_booking_id: "VP-GONE" }]),
      { membership_number: "KC1" },
    )) as { data: any };
    expect(r.data.submissions[0].viewpoint_booking.note).toContain(
      "not found in Viewpoint",
    );
  });

  it("never exposes contact details or free text from the request row", async () => {
    const r = (await getSubmissionLog(ctxWithSubmissions([SUBMISSION]), {
      membership_number: "KC1",
    })) as { status: string };
    const text = JSON.stringify(r);
    expect(text).not.toContain("jane.doe@karma.com");
    expect(text).not.toContain("812 345 678");
    expect(text).not.toContain("comment");
  });

  it("not_found when the member never registered in the app", async () => {
    membersMock.GetMembersByMembershipNumber.mockResolvedValue([
      { member_id: null },
    ]);
    const r = await getSubmissionLog(ctxWithSubmissions([]), {
      membership_number: "KC1",
    });
    expect(r).toMatchObject({ status: "not_found" });
  });

  it("not_found when there are no submissions in the period", async () => {
    const r = await getSubmissionLog(ctxWithSubmissions([]), {
      membership_number: "KC1",
      from: "2026-01-01",
      to: "2026-02-01",
    });
    expect(r).toMatchObject({ status: "not_found" });
  });

  it("over the route: validates date format", async () => {
    const res = await post("/tools/submission-log", {
      conversation_id: "conv-1",
      membership_number: "KC1",
      from: "01/01/2026",
    });
    expect(res.status).toBe(400);
  });
});

// ---------- guru_external_booking_status ----------

const VP_ROW = {
  booking_no: 123456,
  status: "Confirmed",
  booking_source: "RCI Member (non KG)",
  booking_type: "Deposit: RCI Rental",
  booking_channel: null,
  created_by: "vp1",
  account_id: "905167",
  entitle_account_id: null,
  arriving_account_id: null,
  guest_name: "Jane Doe",
  resort_name: "Karma Royal Palms",
  room_type: "T1",
  arrival: new Date("2026-12-01"),
  departure: new Date("2026-12-05"),
  adults: 2,
  children: 0,
  currency: "US$",
  folio_total: 450,
  confirmed_date: new Date("2026-10-01"),
  modify_date: new Date("2026-10-02"),
};

const ctx = {} as never;

describe("guru_external_booking_status", () => {
  it("by booking number: Karma-side view with the vendor-escalation note", async () => {
    findBooking.mockResolvedValue(VP_ROW);
    const r = (await getExternalBookingStatus(ctx, {
      booking_number: "123456",
    })) as { status: string; data: any };
    expect(r.status).toBe("ok");
    expect(r.data.booking).toMatchObject({
      booking_no: 123456,
      status: "Confirmed",
      is_external_exchange: true,
      amount: 450,
      currency: "US$",
    });
    expect(r.data.note).toContain("vendor");
    // guest name is not part of this DTO
    expect(JSON.stringify(r.data)).not.toContain("Jane Doe");
  });

  it("by member: lists only external-exchange bookings, date-filtered", async () => {
    listBookings.mockResolvedValue([
      VP_ROW,
      { ...VP_ROW, booking_no: 2, booking_source: "KC Member", booking_type: "Entitlement Member" },
      { ...VP_ROW, booking_no: 3, arrival: new Date("2027-06-01") },
    ]);
    const r = (await getExternalBookingStatus(ctx, {
      membership_number: "905167",
      from: "2026-01-01",
      to: "2026-12-31",
    })) as { data: any };
    expect(r.data.bookings).toHaveLength(1);
    expect(r.data.bookings[0].booking_no).toBe(123456);
  });

  it("not_found when the booking does not exist in Viewpoint", async () => {
    findBooking.mockResolvedValue(undefined);
    const r = await getExternalBookingStatus(ctx, { booking_number: "999" });
    expect(r).toMatchObject({ status: "not_found" });
    expect((r as { message: string }).message).toContain("vendor");
  });

  it("not_found when the member has no exchange bookings", async () => {
    listBookings.mockResolvedValue([
      { ...VP_ROW, booking_source: "KC Member", booking_type: "Entitlement" },
    ]);
    const r = await getExternalBookingStatus(ctx, {
      membership_number: "905167",
    });
    expect(r).toMatchObject({ status: "not_found" });
  });

  it("errors when neither identifier is given", async () => {
    const r = await getExternalBookingStatus(ctx, {});
    expect(r).toMatchObject({ status: "error" });
  });
});
