import { supabaseAdmin as admin } from "./supabase-admin";
import type { Msg } from "./chat-parser";
import { assess } from "./scoring";
import { applyStage } from "./stages";
import { RANK, type Stage } from "./stage-defs";

// ATC/IC/AddPaymentInfo dikirim otomatis hanya kalau keyakinan AI cukup tinggi.
// Purchase dan lost tidak pernah otomatis: selalu lewat konfirmasi CS.
const AUTO_STAGES: Stage[] = ["product_selected", "checkout", "payment_info"];
const AUTO_CONF = 0.8;
const RETENTION_DAYS = Number(process.env.CHAT_RETENTION_DAYS ?? 90);

export async function ingestChat(p: { orgId: string; leadId: string; userId: string; rawText: string; msgs: Msg[] }) {
  const { orgId, leadId, msgs } = p;
  const first = msgs[0];
  const last = msgs[msgs.length - 1];

  const { data: imp } = await admin
    .from("chat_imports")
    .insert({
      org_id: orgId,
      lead_id: leadId,
      uploaded_by: p.userId,
      raw_text: p.rawText,
      message_count: msgs.length,
      first_message_at: first.ts,
      last_message_at: last.ts,
      expires_at: new Date(Date.now() + RETENTION_DAYS * 864e5).toISOString(),
    })
    .select("id")
    .single();

  // Prefilled message diterima = Contact, dengan waktu pesan pertama
  await applyStage({ orgId, leadId, stage: "contacted", occurredAt: new Date(first.ts), source: "system" });

  const a = await assess(msgs);

  const { data: hist } = await admin.from("lead_stage_history").select("stage").eq("lead_id", leadId);
  const have = new Set<string>((hist ?? []).map((h: { stage: string }) => h.stage));

  let suggestion: { stage: Stage; confidence: number } | null = null;
  const ordered = [...a.stages].sort((x, y) => RANK[x.stage] - RANK[y.stage]);
  for (const s of ordered) {
    if (have.has(s.stage) && s.stage !== "purchased") continue;
    if (AUTO_STAGES.includes(s.stage) && s.confidence >= AUTO_CONF) {
      await applyStage({ orgId, leadId, stage: s.stage, occurredAt: new Date(s.ts), source: "ai_auto", confidence: s.confidence });
    } else if (!suggestion || RANK[s.stage] > RANK[suggestion.stage]) {
      suggestion = { stage: s.stage, confidence: s.confidence };
    }
  }

  await admin.from("lead_scores").insert({
    org_id: orgId,
    lead_id: leadId,
    chat_import_id: imp?.id ?? null,
    score: a.score,
    temperature: a.temperature,
    suggested_stage: suggestion?.stage ?? null,
    stage_confidence: suggestion?.confidence ?? null,
    signals: a.signals,
    reasoning: a.reasoning,
    next_action: a.nextAction,
    model: a.model,
    amount_hint: a.amountHint,
    product_hint: a.productHint,
    stages: a.stages,
  });

  await admin
    .from("leads")
    .update({ score: a.score, temperature: a.temperature, scored_at: new Date().toISOString(), last_message_at: last.ts })
    .eq("id", leadId);

  return { model: a.model };
}
