import type { ExchangeClient } from "../exchange/client.js";
import type { OrderRecord } from "../exchange/types.js";
import type { OrderRow } from "../repos/orders.js";
import type { CounterpartyRow } from "../repos/counterparties.js";
import { markAsked } from "../repos/orders.js";
import { insertOutgoing } from "../repos/chat.js";
import { getEnabledByTrigger, renderTemplate } from "../repos/templates.js";
import { writeAudit } from "../audit/audit.js";

/**
 * Automações de chat baseadas em templates. Cada gatilho dispara no máximo
 * UMA vez por ordem (flags asked_validation / asked_pix). Só dispara se o
 * template do gatilho estiver habilitado.
 *
 * Gatilhos (CLAUDE.md):
 * - paid_new_customer_validation: ordem paga + cliente novo/não-validado ->
 *   pede CPF + telefone.
 * - counterparty_selling_pix: cliente vendendo cripto (anunciante COMPRA) ->
 *   pede a chave PIX.
 */

export interface AutomationContext {
  client: ExchangeClient;
  orderRow: OrderRow;
  record: OrderRecord;
  counterparty: CounterpartyRow | null;
}

export interface AutomationResult {
  fired: string[];
}

export async function runOrderAutomations(ctx: AutomationContext): Promise<AutomationResult> {
  const fired: string[] = [];
  const { orderRow, record, counterparty } = ctx;

  // 1) Validação de cliente novo quando a ordem é paga.
  const isNewCustomer = !counterparty || counterparty.validated === 0;
  if (record.isPaid && isNewCustomer && orderRow.asked_validation === 0) {
    if (await fireTemplate(ctx, "paid_new_customer_validation")) {
      await markAsked(orderRow.id, "validation");
      fired.push("paid_new_customer_validation");
    }
  }

  // 2) Pedir PIX quando o cliente vende cripto (anunciante COMPRA).
  if (record.tradeType === "BUY" && orderRow.asked_pix === 0) {
    if (await fireTemplate(ctx, "counterparty_selling_pix")) {
      await markAsked(orderRow.id, "pix");
      fired.push("counterparty_selling_pix");
    }
  }

  return { fired };
}

async function fireTemplate(
  ctx: AutomationContext,
  trigger: "paid_new_customer_validation" | "counterparty_selling_pix",
): Promise<boolean> {
  const tpl = await getEnabledByTrigger(trigger);
  if (!tpl) return false; // gatilho desligado / sem template

  const { orderRow, counterparty } = ctx;
  const body = renderTemplate(tpl.body, {
    nome: counterparty?.display_name ?? "",
    valor: orderRow.total_price ?? "",
    ordem: orderRow.order_no,
    asset: orderRow.asset,
    fiat: orderRow.fiat,
    amount: orderRow.amount ?? "",
  });

  await ctx.client.sendChatMessage(orderRow.order_no, body);
  await insertOutgoing(orderRow.order_no, orderRow.id, body, true);
  await writeAudit({
    action: "chat.automation",
    entity: "order",
    entityId: orderRow.id,
    detail: { trigger, orderNo: orderRow.order_no },
  });
  return true;
}
