import type { Context } from "hono";
import type { RepositoryContext } from "@/internal/datastore/repository";
import type { GuruTicket } from "@/internal/datastore/guru.types";
import { GuruRepository } from "./guru.repository";
import { redactSensitive } from "@/internal/kevo/kevo.service";
import { MemberRepository } from "@/internal/members/member.repository";
import { MemberUserRepository } from "@/internal/members/member-user.repository";
import { MemberSessionRepository } from "@/internal/member-session/member-session.repository";
import { MemberServices } from "@/internal/members/member.services";
import { AccountDeletionRepository } from "@/internal/account-deletion/account-deletion.repository";
import { AccountDeletionServices } from "@/internal/account-deletion/account-deletion.service";
import { getViewpointDB } from "@/internal/viewpoint-db/kcgm-bookings.repo";
import {
  classifyOrigin,
  findBookingByNumber,
  listBookingsForMemberships,
} from "@/internal/viewpoint-db/signup-bookings.repo";
import { ViewpointBooking } from "@karma/viewpoint-sdk/booking";

/**
 * Read-only diagnosis tools called by the ElevenLabs Guru agent through
 * /v1/guru/tools/* (shared-secret auth; conversation_id is bound to
 * system__conversation_id so the LLM cannot forge it).
 *
 * Every response is a compact, explicitly whitelisted DTO: that is both the
 * PII mask (nothing leaves unless named here) and the payload-size control
 * (the agent reads these aloud / reasons over them).
 *
 * Reads are not audited — per the meeting notes §5, individual API calls
 * are not micro-tracked. Writes (update_ticket) are audited.
 */

// ---- masking ----

export const maskEmail = (email: string | null | undefined): string | null => {
  if (!email) return null;
  const [user, domain] = email.split("@");
  if (!domain) return "[invalid email]";
  const visible = user.slice(0, 2);
  return `${visible}${"*".repeat(Math.max(user.length - 2, 1))}@${domain}`;
};

export const maskPhone = (phone: string | null | undefined): string | null => {
  if (!phone) return null;
  const digits = phone.replace(/\D/g, "");
  if (digits.length < 4) return "****";
  return `****${digits.slice(-2)}`;
};

const servicesFor = (c: Context) =>
  MemberServices({
    MemberRepository: MemberRepository(c as RepositoryContext),
    MemberUserRepository: MemberUserRepository(c as RepositoryContext),
    MemberSessionRepository: MemberSessionRepository(c as RepositoryContext),
  });

const deletionServicesFor = (c: Context) =>
  AccountDeletionServices({
    AccountDeletionRepository: AccountDeletionRepository(
      c as RepositoryContext,
    ),
  });

/** Resolve the ticket a conversation belongs to — the tools' authorization. */
export const ticketForConversation = async (
  c: Context,
  conversationId: string,
): Promise<GuruTicket | null> => {
  const ticket = await GuruRepository(
    c as RepositoryContext,
  ).getTicketByConversation(conversationId);
  return ticket ?? null;
};

/**
 * Console cases already open for a member — duplicate detection. Only covers
 * cases created through this console; the agent cannot search ClickUp itself.
 */
const existingCasesForMember = async (
  c: Context,
  memberRef: string,
  excludeTicketId?: string,
) =>
  (
    await GuruRepository(c as RepositoryContext).listTicketsByMemberRef(
      memberRef,
      excludeTicketId,
    )
  ).map((t) => ({
    reference: t.reference,
    status: t.status,
    category: t.category,
    opened_at: t.created_at,
    clickup_task: t.clickup_task_id ? "created" : "not created yet",
  }));

// ---- tools ----

export type ToolResult =
  | { status: "ok"; data: unknown }
  | { status: "error" | "not_found" | "escalate"; message: string };

const ok = (data: unknown): ToolResult => ({ status: "ok", data });
const notFound = (message: string): ToolResult => ({
  status: "not_found",
  message,
});

/**
 * lookup_member: one of email / membership_number / member_number.
 * Email search aggregates Viewpoint + core (registration state, sessions).
 */
export const lookupMember = async (
  c: Context,
  input: {
    email?: string;
    membership_number?: string;
    member_number?: string;
  },
): Promise<ToolResult> => {
  if (input.email) {
    const results = await deletionServicesFor(c).SearchByEmail(input.email);
    if (!results.length)
      return notFound(
        "No member found for that email in Viewpoint or the app database. Check the spelling with the concierge.",
      );
    return ok(
      results.slice(0, 5).map((r) => ({
        account_number: r.accountNumber,
        viewpoint: r.viewpoint.found
          ? {
              account_type: r.viewpoint.accountType,
              account_status: r.viewpoint.accountStatus,
              joined: r.viewpoint.joinedDate,
            }
          : { found: false },
        app: r.local.found
          ? {
              registered: true,
              members: r.local.members.map((m) => ({
                member_record_id: m.memberID,
                member_number: m.memberNumber,
                email_masked: maskEmail(m.email),
                is_active: m.isActive,
                is_deleted: m.isDeleted,
                user_active: m.userIsActive,
                account_type: m.accountTypeName,
                account_status: m.accountStatusName,
              })),
              active_sessions: r.local.activeSessions,
            }
          : {
              registered: false,
              note: "Exists in Viewpoint but never registered in the app — likely a first-time-login case.",
            },
      })),
    );
  }

  if (input.membership_number) {
    const members = await servicesFor(c).GetMembersByMembershipNumber(
      input.membership_number,
    );
    if (!members?.length)
      return notFound("No Viewpoint account found for that membership number.");
    const existing_cases = await existingCasesForMember(
      c,
      input.membership_number,
    );
    return ok({
      ...(existing_cases.length
        ? {
            existing_cases,
            note: "This member already has console case(s) — tell the concierge and avoid opening a duplicate. Only console-created cases are visible here.",
          }
        : {}),
      members: members.map((m: Record<string, unknown>) => ({
        member_record_id: m.member_id ?? null,
        member_number: m.member_number,
        membership_number: m.membership_number,
        name: [m.first_name, m.last_name].filter(Boolean).join(" ") || null,
        email_masked: maskEmail(m.email as string | null),
        mobile_masked: maskPhone(m.mobile as string | null),
        app_registered: m.member_id != null,
        user_id_present: m.user_id != null,
        is_active: m.is_active,
        account_type: m.account_type_name,
        account_status: m.account_status_name,
        profile_id: m.id ?? null,
      })),
    });
  }

  if (input.member_number) {
    const m = await servicesFor(c).GetMemberByMemberNumber(
      input.member_number,
    );
    if (!m) return notFound("No member found for that member number.");
    const row = m as Record<string, unknown>;
    return ok({
      member_record_id: row.member_id ?? null,
      member_number: row.member_number,
      membership_number: row.membership_number,
      name: [row.first_name, row.last_name].filter(Boolean).join(" ") || null,
      email_masked: maskEmail(row.email as string | null),
      mobile_masked: maskPhone(row.mobile as string | null),
      is_active: row.is_active,
      is_deleted: row.is_deleted,
      user_active: row.user_is_active,
      account_type: row.account_type_name,
      account_status: row.account_status_name,
      profile_id: row.id ?? null,
    });
  }

  return {
    status: "error",
    message:
      "Provide one of: email, membership_number or member_number. Ask the concierge for it.",
  };
};

/** get_member_overview: last app session, booking counts — per account. */
export const getMemberOverview = async (
  c: Context,
  membershipNumber: string,
): Promise<ToolResult> => {
  const overview = await servicesFor(c).GetAccountOverview(membershipNumber);
  if (!overview) return notFound("No account found for that membership number.");
  const o = overview as Record<string, unknown> & {
    lastSession?: Record<string, unknown> | null;
  };
  return ok({
    last_session: o.lastSession
      ? {
          at: o.lastSession.created_at,
          app: o.lastSession.application_type,
          app_version: o.lastSession.application_version,
          os: o.lastSession.os,
          device: o.lastSession.device_type,
        }
      : {
          note: "No app sessions recorded — the member may never have logged in.",
        },
    booking_counts: o.bookingTotals ?? o.bookings ?? null,
  });
};

/** get_bookings: recent bookings for an account from the live Viewpoint DB. */
export const getBookings = async (
  _c: Context,
  membershipNumber: string,
): Promise<ToolResult> => {
  const rows = await listBookingsForMemberships(getViewpointDB(), [
    membershipNumber,
  ]);
  if (!rows.length)
    return notFound(
      "No Viewpoint bookings found for that account. Subito-only bookings may still exist in the app.",
    );
  return ok(
    rows.slice(0, 20).map((b) => ({
      booking_no: b.booking_no,
      status: b.status,
      resort: b.resort_name,
      room_type: b.room_type,
      arrival: b.arrival,
      departure: b.departure,
      source: classifyOrigin(b.created_by),
      confirmed: b.confirmed_date,
    })),
  );
};

/**
 * get_booking: a single Viewpoint booking by number. Reads the same
 * Viewpoint DB view as get_bookings (so the two tools never disagree),
 * with the REST API as a fallback for bookings not yet in the view.
 */
export const getBooking = async (
  _c: Context,
  bookingNumber: string,
): Promise<ToolResult> => {
  const row = await findBookingByNumber(getViewpointDB(), bookingNumber);
  if (row)
    return ok({
      booking_no: row.booking_no,
      status: row.status,
      resort: row.resort_name,
      room_type: row.room_type,
      arrival: row.arrival,
      departure: row.departure,
      source: classifyOrigin(row.created_by),
      confirmed: row.confirmed_date,
      guest_name: row.guest_name,
    });
  const { booking, error } = await new ViewpointBooking().getBooking(
    bookingNumber,
  );
  if (error) return { status: "error", message: "Viewpoint lookup failed." };
  if (!booking)
    return notFound("No Viewpoint booking found with that number.");
  const b = booking as unknown as Record<string, unknown>;
  return ok({
    booking_no: bookingNumber,
    status: b.Status ?? b.status ?? null,
    resort: b.Resort ?? b.resort ?? null,
    arrival: b.ArrivalDate ?? b.arrival ?? null,
    departure: b.DepartureDate ?? b.departure ?? null,
  });
};

/** get_points: Viewpoint points balance per account. */
export const getPoints = async (
  c: Context,
  membershipNumber: string,
): Promise<ToolResult> => {
  const result = await servicesFor(c).GetMemberPointsBalance(membershipNumber);
  if (!result) return notFound("No points data found for that account.");
  const r = result as { balance?: unknown; entitlements?: unknown[] };
  return ok({
    balance: r.balance ?? null,
    entitlement_lines: Array.isArray(r.entitlements)
      ? r.entitlements.length
      : 0,
  });
};

/**
 * get_entitlements: contracts + points entitlement lines, server-side by
 * membership number (the admin entitlement lookup from the meeting notes §6 —
 * no member session token anywhere).
 *
 * clubResortID 0 is authoritative: it returns the union of all points clubs
 * (verified 13 Nov 2026 against member 905167, whose balance lives in a club
 * the India/non-India home-club heuristic misses — home club showed 0, club 0
 * showed the real 749). Each line carries its club name instead.
 *
 * Contracts are whitelisted hard: upstream CRMData contains card numbers and
 * purchase prices and must never reach the agent.
 */
export const getEntitlements = async (
  c: Context,
  membershipNumber: string,
): Promise<ToolResult> => {
  const { getViewPointAccountById } = await import(
    "@/internal/viewpoint/member"
  );
  const { getMemberPoints } = await import("@/viewpoint");
  const { ViewpointMember } = await import("@karma/viewpoint-sdk/member");

  let upstreamFailed = false;
  const nullOnError = <T>(p: Promise<T>): Promise<T | null> =>
    p.catch(() => {
      upstreamFailed = true;
      return null;
    });
  // getViewPointAccountById already maps 404 → null and throws otherwise.
  const [account, contracts, points] = await Promise.all([
    nullOnError(getViewPointAccountById(membershipNumber)),
    nullOnError(new ViewpointMember().getContracts(membershipNumber)),
    nullOnError(getMemberPoints(membershipNumber, 0)),
  ]);
  if (!account && !contracts?.length && !points?.length)
    return upstreamFailed
      ? { status: "error", message: "Viewpoint lookup failed. Try once more." }
      : notFound(
          "No Viewpoint account, contracts or entitlements found for that membership number.",
        );

  const today = new Date().toISOString().slice(0, 10);
  return ok({
    account: account
      ? {
          account_type: account.AccountType ?? null,
          account_status: account.AccountStatus ?? null,
          service_center: account.ServiceCenter ?? null,
        }
      : { note: "Account record not found in Viewpoint." },
    contracts: (contracts ?? []).map((ct) => ({
      contract_ref: ct.ExternalContractID,
      inventory_type: ct.InventoryType,
      quantity: ct.Quantity,
      unit_type: ct.UnitTypeDesc,
      week_type: ct.WeekTypeDesc,
      resort: ct.ResortName,
      term_years: ct.Term,
      commence: ct.CommenceDate,
      expiry: ct.ExpiryDate,
      expired: Boolean(ct.ExpiryDate && String(ct.ExpiryDate) < today),
      fee_paid: Boolean(ct.PaidDate),
    })),
    entitlements: (Array.isArray(points) ? points : []).map((p) => ({
      club: p.PointsClubName ?? null,
      type: p.PointsType ?? null,
      status: p.Status ?? null,
      year: p.EntitlementYear ?? null,
      issued: p.Issued ?? null,
      balance: p.Balance ?? null,
      expiry: p.ExpiryDate ?? null,
    })),
    club_resort_id_used: 0,
    note:
      "Entitlement lines cover ALL points clubs (clubResortID 0). The app may show only one club's " +
      "balance. Product-matrix flags (affiliate access, unit-type restrictions, Subito login allowed) " +
      "are NOT available here — escalate if the issue depends on them.",
  });
};

// ---- external booking status (Viewpoint half) ----

/** Exchange/vendor-programme markers seen in bookingsource/type/channel. */
const EXTERNAL_MARKER =
  /rci|outgoing|exchange|escape|7across|getaway|deposit/i;

const isExternalExchange = (b: {
  booking_source: string | null;
  booking_type: string | null;
  booking_channel: string | null;
}): boolean =>
  EXTERNAL_MARKER.test(
    [b.booking_source, b.booking_type, b.booking_channel]
      .filter(Boolean)
      .join(" "),
  );

const externalBookingDTO = (b: import("@/internal/viewpoint-db/signup-bookings.repo").SignupBookingRow) => ({
  booking_no: b.booking_no,
  status: b.status,
  booking_source: b.booking_source,
  booking_type: b.booking_type,
  booking_channel: b.booking_channel,
  resort: b.resort_name,
  arrival: b.arrival,
  departure: b.departure,
  confirmed: b.confirmed_date,
  last_modified: b.modify_date,
  amount: b.folio_total,
  currency: b.currency,
  is_external_exchange: isExternalExchange(b),
});

/**
 * get_external_booking_status: the KARMA-side view of RCI / Weekly Escapes /
 * 7Across / Getaways bookings — presence, dates, status, amount. The vendor
 * systems are not connected (handover §2.5 decision 13 Nov 2026): vendor-side
 * state always escalates. Never any card data — amount and status only.
 */
export const getExternalBookingStatus = async (
  c: Context,
  input: {
    booking_number?: string;
    membership_number?: string;
    from?: string;
    to?: string;
  },
): Promise<ToolResult> => {
  const db = getViewpointDB();
  const vendorNote =
    "This is the Karma/Viewpoint side only. The vendor's own system (RCI, Weekly Escapes, " +
    "7Across, Getaways) is not connected — if the question is about the vendor-side state " +
    "(e.g. dates differ at RCI), escalate with these details.";

  if (input.booking_number) {
    const row = await findBookingByNumber(db, input.booking_number);
    if (!row)
      return notFound(
        "No booking with that number exists in Viewpoint. If the member has a vendor confirmation, the booking may exist only on the vendor side — escalate.",
      );
    return ok({ booking: externalBookingDTO(row), note: vendorNote });
  }

  if (input.membership_number) {
    let rows = (
      await listBookingsForMemberships(db, [input.membership_number])
    ).filter(isExternalExchange);
    const iso = (d: Date | null) =>
      d ? new Date(d).toISOString().slice(0, 10) : null;
    if (input.from) rows = rows.filter((r) => (iso(r.arrival) ?? "") >= input.from!);
    if (input.to) rows = rows.filter((r) => (iso(r.arrival) ?? "9999") <= input.to!);
    if (!rows.length)
      return notFound(
        "No external-exchange (RCI / Weekly Escapes / 7Across / Getaways style) bookings found for that member in Viewpoint for the requested period.",
      );
    return ok({
      bookings: rows.slice(0, 20).map(externalBookingDTO),
      note: vendorNote,
    });
  }

  return {
    status: "error",
    message: "Provide booking_number, or membership_number (optionally with from/to dates).",
  };
};

// ---- availability ----

type DateRangeEntry = { label?: string; start_date: string; end_date: string };
type OpenClosePeriod = DateRangeEntry & {
  period_type: "ONE_OFF" | "RECURRING_ANNUAL";
  start_month_day?: string;
  end_month_day?: string;
};

/** [start,end] (inclusive) overlaps the stay [arrival, lastNight]? Lexical YYYY-MM-DD. */
const overlapsStay = (
  start: string | undefined,
  end: string | undefined,
  arrival: string,
  lastNight: string,
): boolean => Boolean(start && end && start <= lastNight && end >= arrival);

const addDays = (iso: string, days: number): string => {
  const d = new Date(`${iso}T00:00:00Z`);
  d.setUTCDate(d.getUTCDate() + days);
  return d.toISOString().slice(0, 10);
};

/** Closure periods: ONE_OFF by dates; RECURRING_ANNUAL by MM-DD, handling year wrap. */
const closureHits = (
  periods: OpenClosePeriod[],
  arrival: string,
  lastNight: string,
): string[] => {
  const hits: string[] = [];
  for (const p of periods) {
    if (p.period_type === "RECURRING_ANNUAL" && p.start_month_day && p.end_month_day) {
      const y0 = Number(arrival.slice(0, 4));
      const y1 = Number(lastNight.slice(0, 4));
      for (let y = y0 - 1; y <= y1; y++) {
        const start = `${y}-${p.start_month_day}`;
        const wraps = p.end_month_day < p.start_month_day;
        const end = `${wraps ? y + 1 : y}-${p.end_month_day}`;
        if (overlapsStay(start, end, arrival, lastNight)) {
          hits.push(p.label ?? `annual closure ${p.start_month_day} to ${p.end_month_day}`);
          break;
        }
      }
    } else if (overlapsStay(p.start_date, p.end_date, arrival, lastNight)) {
      hits.push(p.label ?? `closed ${p.start_date} to ${p.end_date}`);
    }
  }
  return hits;
};

/**
 * get_availability: per-unit nightly inventory from Viewpoint plus the
 * configured rules that block a stay — the "why" (closure, blackout, booking
 * horizon) matters more than the raw counts: most "no availability" cases
 * are a rule, not an empty resort.
 *
 * Tier/member-specific pricing rules are NOT evaluated here (they need the
 * member's contract roles); hot deals overlapping the stay are listed with a
 * tier_restricted flag instead so the agent can reason about visibility.
 */
export const getAvailability = async (
  c: Context,
  input: {
    resort_code: string;
    arrival: string;
    departure: string;
    unit_code?: string;
  },
): Promise<ToolResult> => {
  const { resort_code, arrival, departure, unit_code } = input;
  if (!/^\d{4}-\d{2}-\d{2}$/.test(arrival) || !/^\d{4}-\d{2}-\d{2}$/.test(departure))
    return { status: "error", message: "Dates must be YYYY-MM-DD." };
  if (arrival >= departure)
    return { status: "error", message: "arrival must be before departure." };

  // The generated DB types predate the resorts migration — type the one table
  // we read (same gap the availability controller works around untyped).
  const db = (c as RepositoryContext).get("datastore") as unknown as import("kysely").Kysely<{
    resorts: {
      code: string | null;
      name: string;
      is_active: boolean;
      blackout_periods: unknown;
      open_close_periods: unknown;
    };
  }>;
  const resort = await db
    .selectFrom("resorts")
    .where("code", "=", resort_code)
    .select(["name", "is_active", "blackout_periods", "open_close_periods"])
    .executeTakeFirst();
  if (!resort)
    return notFound(
      "No resort found with that code. Ask the concierge which resort, or use the Viewpoint resort code.",
    );

  const lastNight = addDays(departure, -1);
  const today = new Date().toISOString().slice(0, 10);

  const blockedBy: Array<{ rule: string; detail: string }> = [];
  if (!resort.is_active)
    blockedBy.push({ rule: "resort_inactive", detail: "Resort is not active in the console." });
  const horizonLimit = addDays(today, 365 * 2);
  if (arrival > horizonLimit)
    blockedBy.push({
      rule: "booking_horizon",
      detail: `Arrival is beyond the default two-year booking horizon (approx. bookable up to ${horizonLimit}); the property's configured booking window may differ.`,
    });
  for (const hit of closureHits(
    (resort.open_close_periods ?? []) as OpenClosePeriod[],
    arrival,
    lastNight,
  ))
    blockedBy.push({ rule: "resort_closure", detail: hit });
  for (const b of (resort.blackout_periods ?? []) as DateRangeEntry[])
    if (overlapsStay(b.start_date, b.end_date, arrival, lastNight))
      blockedBy.push({
        rule: "blackout",
        detail: b.label ?? `blackout ${b.start_date} to ${b.end_date}`,
      });

  const { ViewpointDestination } = await import(
    "@karma/viewpoint-sdk/destination"
  );
  let inventory: Awaited<
    ReturnType<InstanceType<typeof ViewpointDestination>["findDestinationUnit"]>
  > = [];
  let inventoryError = false;
  try {
    inventory = await new ViewpointDestination().findDestinationUnit(
      resort_code,
      arrival,
      departure,
    );
  } catch {
    inventoryError = true;
  }
  const wanted = unit_code?.trim().toUpperCase();
  const units = inventory
    .filter((u) => !wanted || u.UnitCategoryCode?.toUpperCase() === wanted)
    .map((u) => {
      const nights = (u.Days ?? []).slice(0, 60);
      const soldOut = nights.filter((d) => !d.UnitCount).map((d) => d.Date);
      return {
        unit_code: u.UnitCategoryCode,
        unit_type: u.UnitCategory,
        available_every_night: nights.length > 0 && soldOut.length === 0,
        sold_out_nights: soldOut,
        min_units_free: nights.length
          ? Math.min(...nights.map((d) => d.UnitCount ?? 0))
          : 0,
      };
    });
  if (!units.length && !inventoryError && !blockedBy.length)
    blockedBy.push({
      rule: "no_inventory",
      detail: wanted
        ? `Viewpoint returned no inventory for unit type ${wanted} at this resort for these dates.`
        : "Viewpoint returned no unit inventory for this resort and date range.",
    });

  const { loadHotDeals } = await import(
    "@/controllers/admin/availability/availability.controller"
  );
  const now = Date.now();
  const hotDeals = Object.entries(loadHotDeals())
    .filter(([, o]) => o.resort === resort.name)
    .filter(([, o]) => {
      const startsOk = !o.starts || now >= new Date(o.starts).getTime();
      const expiresOk = !o.expires || now <= new Date(o.expires).getTime();
      return startsOk && expiresOk;
    })
    .map(([key, o]) => ({
      hot_deal_id: key,
      travel_windows: o.travel_between ?? [],
      covers_these_dates: (o.travel_between ?? []).some(([s, e]) =>
        overlapsStay(s, e, arrival, lastNight),
      ),
      unit_codes: o.unit_code ?? [],
      tier_restricted: Array.isArray(o.roles) && o.roles.length > 0,
    }));

  const daysUntilArrival = Math.round(
    (Date.parse(`${arrival}T00:00:00Z`) - Date.parse(`${today}T00:00:00Z`)) /
      86400_000,
  );
  return ok({
    resort: resort.name,
    arrival,
    departure,
    blocked_by: blockedBy,
    available: blockedBy.length === 0 && units.some((u) => u.available_every_night),
    units,
    ...(inventoryError
      ? { inventory_note: "Viewpoint inventory lookup failed — rule checks above still apply." }
      : {}),
    hot_deals_at_resort: hotDeals,
    days_until_arrival: daysUntilArrival,
    within_90_days: daysUntilArrival <= 90,
    note:
      "blocked_by explains WHY dates are unavailable — lead with that. within_90_days supports " +
      "90-day-rule playbooks. Member-tier pricing rules are not evaluated here; if the issue " +
      "depends on the member's tier seeing a specific rate, escalate.",
  });
};

/**
 * get_submission_log: booking/hold requests the member submitted from the app
 * or website (member DB booking_requests) and whether each one landed as a
 * Viewpoint booking — the "I booked but nothing shows" diagnosis. Free-text
 * fields (comment/note) and contact columns are never returned.
 */
export const getSubmissionLog = async (
  c: Context,
  input: { membership_number: string; from?: string; to?: string },
): Promise<ToolResult> => {
  const members = await servicesFor(c).GetMembersByMembershipNumber(
    input.membership_number,
  );
  const memberIds = (members ?? [])
    .map((m: Record<string, unknown>) => m.member_id)
    .filter((id: unknown): id is string | number => id != null);
  if (!memberIds.length)
    return notFound(
      "No app member record found for that membership number — the member may never have registered in the app, so there can be no app submissions.",
    );

  const memberDb = (c as RepositoryContext).get(
    "memberDatastore",
  ) as unknown as import("kysely").Kysely<{
    booking_requests: {
      id: string;
      member_id: string;
      type: string;
      status: string;
      ext_booking_id: string | null;
      guest_count: number | null;
      created_at: Date;
    };
  }>;
  let q = memberDb
    .selectFrom("booking_requests")
    .where("member_id", "in", memberIds as string[])
    .select(["type", "status", "ext_booking_id", "guest_count", "created_at"])
    .orderBy("created_at", "desc")
    .limit(20);
  if (input.from) q = q.where("created_at", ">=", new Date(`${input.from}T00:00:00Z`));
  if (input.to) q = q.where("created_at", "<=", new Date(`${input.to}T23:59:59Z`));
  const rows = await q.execute();
  if (!rows.length)
    return notFound(
      "No app/website booking submissions found for that member in the requested period.",
    );

  const db = getViewpointDB();
  const submissions = await Promise.all(
    rows.map(async (r) => {
      const vp = r.ext_booking_id
        ? await findBookingByNumber(db, r.ext_booking_id).catch(() => null)
        : null;
      return {
        submitted_at: r.created_at,
        type: r.type,
        request_status: r.status,
        guest_count: r.guest_count,
        viewpoint_booking: vp
          ? {
              booking_no: vp.booking_no,
              status: vp.status,
              arrival: vp.arrival,
              departure: vp.departure,
            }
          : r.ext_booking_id
            ? { booking_no: r.ext_booking_id, note: "Referenced booking not found in Viewpoint." }
            : {
                note: "No Viewpoint booking recorded for this submission — it did not create an on-hold booking.",
              },
      };
    }),
  );
  return ok({ submissions });
};

/**
 * ticket_history: the bound ticket's state plus its ClickUp history
 * (comments include PM updates) — how the agent regains context when a
 * concierge reopens a case. Everything is redacted before it reaches the LLM.
 */
export const getTicketHistory = async (
  c: Context,
  ticket: GuruTicket,
): Promise<ToolResult> => {
  const base = {
    reference: ticket.reference,
    status: ticket.status,
    category: ticket.category,
    member_ref: ticket.member_ref,
    summary: ticket.summary,
    opened_at: ticket.created_at,
    other_cases_for_member: ticket.member_ref
      ? await existingCasesForMember(c, ticket.member_ref, ticket.id)
      : [],
  };
  if (!ticket.clickup_task_id)
    return ok({
      ...base,
      history: [],
      note: "No ClickUp task for this case yet — it is created automatically after the chat ends (or when the first screenshot is attached). Do not tell the concierge a ClickUp task already exists.",
    });
  const { getClickUpTaskComments } = await import("@/lib/clickup/client");
  const comments = await getClickUpTaskComments(ticket.clickup_task_id);
  return ok({
    ...base,
    history: comments
      .slice(0, 25)
      .reverse() // oldest first, reads chronologically
      .map((cm) => ({
        at: cm.date ? new Date(Number(cm.date)).toISOString() : null,
        by: cm.user?.username ?? "unknown",
        text: redactSensitive(cm.comment_text ?? "").slice(0, 1500),
      })),
  });
};

/** update_ticket: the agent classifies/annotates the bound ticket. Audited. */
export const updateTicket = async (
  c: Context,
  ticket: GuruTicket,
  input: { member_ref?: string; category?: string; summary?: string },
): Promise<ToolResult> => {
  const repo = GuruRepository(c as RepositoryContext);
  const patch: Record<string, string> = {};
  if (input.member_ref) patch.member_ref = input.member_ref;
  if (input.category) patch.category = input.category.toLowerCase();
  if (input.summary) patch.summary = redactSensitive(input.summary);
  if (!Object.keys(patch).length)
    return { status: "error", message: "Nothing to update." };

  await repo.updateTicket(ticket.id, patch);
  await repo.insertAudit({
    ticket_id: ticket.id,
    action: "ticket.updated_by_agent",
    actor_email: ticket.concierge_email,
    member_ref: input.member_ref ?? ticket.member_ref,
    metadata: { fields: Object.keys(patch) },
  });
  return ok({ reference: ticket.reference, updated: Object.keys(patch) });
};
