import * as crypto from "node:crypto";
import type { Context } from "hono";
import type { Kysely } from "kysely";
import type { DB } from "@/internal/datastore/db";
import type { RepositoryContext } from "@/internal/datastore/repository";
import { BaseRepository } from "@/internal/datastore/repository";
import type {
  GuruPendingAction,
  GuruTicket,
} from "@/internal/datastore/guru.types";
import { GuruRepository } from "./guru.repository";
import { GuruServices } from "./guru.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 { EDMService } from "@/v1/services/admin/edm/edm.service";
import { forwardToUpdotCore } from "@/lib/updot-forward";
import { createClickUpTaskComment } from "@/lib/clickup/client";
import { logError } from "@/lib/logger";

/**
 * The write path (docs/subito-ai-guru.md §2 — "writes never flow through the
 * LLM"). The agent's propose_action tool only creates a PENDING row here.
 * Execution happens exclusively in confirmAction, on the authenticated
 * console session, after a server-side edit-allowlist check. A forged or
 * injected tool call can at worst create a card nobody unauthorised can
 * confirm.
 *
 * Secrets: the one-time password is returned ONCE in the confirm response
 * (`display`) and never stored — not in guru_pending_actions.result, not in
 * the audit log, not in ClickUp.
 */

export const ACTION_EXPIRY_MINUTES = 15;

export type ProposeActionInput = {
  conversation_id: string;
  action_type:
    | "PASSWORD_RESET"
    | "SEND_VERIFICATION_EDM"
    | "SYNC_PROFILE"
    | "RESEND_RCI_CONFIRMATION_EDM";
  member_ref: string;
  summary: string;
  member_record_id?: string;
  email?: string;
  profile_id?: string;
  rci_unit_id?: string;
};

const repoFor = (c: Context) => GuruRepository(c as RepositoryContext);

/** Human-readable card line, built server-side so the card can't lie. */
const cardSummary = (input: ProposeActionInput): string => {
  switch (input.action_type) {
    case "PASSWORD_RESET":
      return `Set a new one-time password for member ${input.member_ref}. The current password stops working immediately.`;
    case "SEND_VERIFICATION_EDM":
      return `Send the account-verification email to member ${input.member_ref}.`;
    case "SYNC_PROFILE":
      return `Sync member ${input.member_ref}'s profile from the old system to Core.`;
    case "RESEND_RCI_CONFIRMATION_EDM":
      return `Resend the RCI confirmation email for member ${input.member_ref} (RCI unit ${input.rci_unit_id}).`;
  }
};

const PARAM_REQUIREMENTS: Record<
  ProposeActionInput["action_type"],
  Array<keyof ProposeActionInput>
> = {
  PASSWORD_RESET: ["member_record_id"],
  SEND_VERIFICATION_EDM: ["email"],
  SYNC_PROFILE: ["profile_id"],
  RESEND_RCI_CONFIRMATION_EDM: ["rci_unit_id", "member_record_id"],
};

export const proposeAction = async (
  c: Context,
  ticket: GuruTicket,
  input: ProposeActionInput,
): Promise<
  | { status: "ok"; data: unknown }
  | { status: "error"; message: string }
> => {
  const missing = PARAM_REQUIREMENTS[input.action_type].filter(
    (p) => !input[p],
  );
  if (missing.length) {
    return {
      status: "error",
      message: `${input.action_type} needs ${missing.join(", ")}. Use guru_lookup_member to find it first.`,
    };
  }

  const repo = repoFor(c);
  const action = await repo.insertPendingAction({
    ticket_id: ticket.id,
    conversation_id: input.conversation_id,
    action_type: input.action_type,
    member_ref: input.member_ref,
    params: {
      member_record_id: input.member_record_id,
      email: input.email,
      profile_id: input.profile_id,
      rci_unit_id: input.rci_unit_id,
    },
    summary: cardSummary(input),
    expires_at: new Date(Date.now() + ACTION_EXPIRY_MINUTES * 60_000),
  });
  await repo.insertAudit({
    ticket_id: ticket.id,
    action_id: action.id,
    action: "action.proposed",
    actor_email: ticket.concierge_email,
    member_ref: input.member_ref,
    metadata: { action_type: input.action_type },
  });
  return {
    status: "ok",
    data: {
      action_id: action.id,
      proposed: input.action_type,
      note:
        "A confirmation card is now showing in the Console. Nothing has been changed yet. " +
        "Ask the concierge to review and press Confirm, then wait for their reply.",
    },
  };
};

// ---- executors ----

type ExecResult =
  | { ok: true; result: Record<string, unknown>; display?: Record<string, unknown> }
  | { ok: false; error: string };

const executePasswordReset = async (
  c: Context,
  memberRecordId: string,
): Promise<ExecResult> => {
  const services = MemberServices({
    MemberRepository: MemberRepository(c as RepositoryContext),
    MemberUserRepository: MemberUserRepository(c as RepositoryContext),
    MemberSessionRepository: MemberSessionRepository(c as RepositoryContext),
  });
  // One-time random password (spec §3: never a shared default).
  const oneTime = crypto.randomBytes(9).toString("base64url");
  const updated = await services.UpdateMemberPassword(memberRecordId, oneTime);
  if (!updated)
    return {
      ok: false,
      error: "This member has no app user account — a password cannot be set.",
    };
  return {
    ok: true,
    result: { password_set: true },
    display: { one_time_password: oneTime },
  };
};

const executeVerificationEdm = async (
  c: Context,
  email: string,
): Promise<ExecResult> => {
  const templateId = process.env.GURU_VERIFICATION_EDM_TEMPLATE_ID?.trim();
  if (!templateId)
    return {
      ok: false,
      error:
        "No verification EDM template is configured (GURU_VERIFICATION_EDM_TEMPLATE_ID). Escalate instead.",
    };
  const res = await EDMService.getInstance().sendTestEmail(
    c.get("datastore") as Kysely<DB>,
    templateId,
    email,
  );
  if (!res.success)
    return { ok: false, error: res.message || "The email could not be sent." };
  return { ok: true, result: { email_sent: true } };
};

const executeResendRciEdm = async (
  c: Context,
  rciUnitId: string,
  memberRecordId: string,
): Promise<ExecResult> => {
  if (!/^\d+$/.test(rciUnitId))
    return { ok: false, error: "RCI unit id must be numeric." };
  const unit = await new BaseRepository(c as RepositoryContext).memberDatastore
    .selectFrom("booking_units")
    .innerJoin("bookings", "bookings.id", "booking_units.booking_id")
    .where("booking_units.id", "=", rciUnitId)
    .where("bookings.member_id", "=", memberRecordId)
    .select("booking_units.id")
    .executeTakeFirst();
  if (!unit)
    return {
      ok: false,
      error: `No booking unit ${rciUnitId} found for this member, so nothing was sent.`,
    };
  const { BookingsService } = await import(
    "@/v1/services/admin/bookings/bookings.service"
  );
  try {
    await BookingsService.getInstance().sendRCIUnitEDM(rciUnitId, {
      memberRecordID: memberRecordId,
    });
    return { ok: true, result: { rci_confirmation_resent: true } };
  } catch (err) {
    return {
      ok: false,
      error: `RCI confirmation resend failed: ${err instanceof Error ? err.message.slice(0, 200) : "upstream error"}`,
    };
  }
};

const executeSyncProfile = async (profileId: string): Promise<ExecResult> => {
  const res = await forwardToUpdotCore(
    `/v1/admin/members/sync-profile/${encodeURIComponent(profileId)}`,
    { method: "PUT", body: JSON.stringify({}) },
  );
  if (!res.ok) {
    const text = await res.text().catch(() => "");
    return {
      ok: false,
      error: `Profile sync failed (${res.status}). ${text.slice(0, 200)}`,
    };
  }
  return { ok: true, result: { profile_synced: true } };
};

// ---- confirm / decline ----

export type ConfirmOutcome =
  | { kind: "not_found" }
  | { kind: "already_handled"; status: string }
  | { kind: "expired" }
  | { kind: "refused" }
  | { kind: "executed"; display?: Record<string, unknown> }
  | { kind: "failed"; error: string };

export const confirmAction = async (
  c: Context,
  actionId: string,
  actor: { id: string; email: string },
): Promise<ConfirmOutcome> => {
  const repo = repoFor(c);
  const action = await repo.getPendingAction(actionId);
  if (!action) return { kind: "not_found" };
  const ticket = await repo.getTicketById(action.ticket_id);
  // Only the concierge who owns the case sees (and can confirm) its cards.
  if (!ticket || ticket.console_user_id !== actor.id)
    return { kind: "not_found" };
  if (action.status !== "PENDING")
    return { kind: "already_handled", status: action.status };

  if (new Date(action.expires_at).getTime() < Date.now()) {
    await repo.transitionAction(action.id, { status: "EXPIRED" });
    await repo.insertAudit({
      ticket_id: ticket.id,
      action_id: action.id,
      action: "action.expired",
      actor_email: actor.email,
      member_ref: action.member_ref,
      success: false,
    });
    return { kind: "expired" };
  }

  // THE gate (spec §3): the logged-in user must be on the edit allowlist.
  // Never derived from anything the LLM or the client asserts.
  const services = GuruServices({ GuruRepository: repo });
  if (!(await services.canEdit(actor.email))) {
    await repo.transitionAction(action.id, {
      status: "REFUSED",
      confirmed_by: actor.email,
    });
    await repo.insertAudit({
      ticket_id: ticket.id,
      action_id: action.id,
      action: "action.refused",
      actor_email: actor.email,
      confirmed_by: actor.email,
      member_ref: action.member_ref,
      clickup_task_id: ticket.clickup_task_id,
      success: false,
      metadata: { reason: "not on edit allowlist" },
    });
    return { kind: "refused" };
  }

  // Claim the row before executing — the PENDING-guarded transition makes
  // double-clicks and concurrent confirms race-safe (one winner).
  const claimed = await repo.transitionAction(action.id, {
    status: "EXECUTED", // optimistic; flipped to FAILED below on error
    confirmed_by: actor.email,
    executed_at: new Date(),
  });
  if (!claimed) return { kind: "already_handled", status: "PENDING" };

  const params = (action.params ?? {}) as Record<string, string | undefined>;
  let exec: ExecResult;
  try {
    switch (action.action_type) {
      case "PASSWORD_RESET":
        exec = await executePasswordReset(c, params.member_record_id ?? "");
        break;
      case "SEND_VERIFICATION_EDM":
        exec = await executeVerificationEdm(c, params.email ?? "");
        break;
      case "SYNC_PROFILE":
        exec = await executeSyncProfile(params.profile_id ?? "");
        break;
      case "RESEND_RCI_CONFIRMATION_EDM":
        exec = await executeResendRciEdm(
          c,
          params.rci_unit_id ?? "",
          params.member_record_id ?? "",
        );
        break;
      default:
        exec = { ok: false, error: "Unknown action type." };
    }
  } catch (err) {
    logError(`[Guru] action ${action.id} execution threw: ${err}`);
    exec = { ok: false, error: "The action failed unexpectedly." };
  }

  // Record the outcome (result never contains the one-time password).
  await repo.updatePendingActionOutcome(action.id, {
    status: exec.ok ? "EXECUTED" : "FAILED",
    result: exec.ok ? exec.result : null,
    error: exec.ok ? null : exec.error,
  });
  await repo.insertAudit({
    ticket_id: ticket.id,
    action_id: action.id,
    action: exec.ok ? "action.executed" : "action.failed",
    actor_email: ticket.concierge_email,
    confirmed_by: actor.email,
    member_ref: action.member_ref,
    clickup_task_id: ticket.clickup_task_id,
    success: exec.ok,
    after: exec.ok ? exec.result : null,
    metadata: {
      action_type: action.action_type,
      ...(exec.ok ? {} : { error: exec.error }),
    },
  });

  // Best-effort ClickUp trail.
  if (ticket.clickup_task_id) {
    createClickUpTaskComment(
      ticket.clickup_task_id,
      `${action.action_type} on member ${action.member_ref} — ${
        exec.ok ? "EXECUTED" : `FAILED: ${exec.ok === false ? exec.error : ""}`
      } (confirmed by ${actor.email})`,
    ).catch((err) => logError(`[Guru] ClickUp action comment failed: ${err}`));
  }

  return exec.ok
    ? { kind: "executed", display: exec.display }
    : { kind: "failed", error: exec.error };
};

export const declineAction = async (
  c: Context,
  actionId: string,
  actor: { id: string; email: string },
): Promise<"declined" | "not_found" | "already_handled"> => {
  const repo = repoFor(c);
  const action = await repo.getPendingAction(actionId);
  if (!action) return "not_found";
  const ticket = await repo.getTicketById(action.ticket_id);
  if (!ticket || ticket.console_user_id !== actor.id) return "not_found";
  const done = await repo.transitionAction(action.id, {
    status: "DECLINED",
    confirmed_by: actor.email,
  });
  if (!done) return "already_handled";
  await repo.insertAudit({
    ticket_id: ticket.id,
    action_id: action.id,
    action: "action.declined",
    actor_email: actor.email,
    confirmed_by: actor.email,
    member_ref: action.member_ref,
    success: false,
  });
  return "declined";
};

/** Console-facing DTO: params/result stay server-side (may hold emails). */
export const toActionDTO = (a: GuruPendingAction) => ({
  id: a.id,
  ticket_id: a.ticket_id,
  action_type: a.action_type,
  member_ref: a.member_ref,
  summary: a.summary,
  status: a.status,
  confirmed_by: a.confirmed_by,
  error: a.error,
  expires_at: a.expires_at,
  created_at: a.created_at,
  executed_at: a.executed_at,
});
