import { CrmActivityType, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { notify } from '../crm/crm-notify';
import { crmUrl } from '../crm/crm-mail';
import { fullName } from '../crm/crm-contacts.service';
import { leadFromWhatsApp, onWhatsAppButton, onWhatsAppKeyword } from '../crm/crm-touch.service';

/**
 * What the WhatsApp webhook does with an event (12 Oct 2026).
 *
 * Delivery receipts move an outbound row forward — sent → delivered → read —
 * and never back: Meta can deliver "read" before "delivered". "failed" keeps
 * Meta's reason. Receipts for messages we have no row for (sent before this
 * release, or by another system on the number) are ignored.
 *
 * A reply is one HostelCare number shared by every hostel, so it is matched
 * in this order:
 *   1. the message it quotes, or the last message we sent that number in the
 *      past 30 days → that hostel and student;
 *   2. a CRM contact with that number → the contact's timeline (platform);
 *   3. a student or guardian with that number → their hostel;
 *   4. otherwise a new CRM lead (L4), unless the number is on a hostel account.
 */

const RECENT_DAYS = 30;
const DAY = 86_400_000;

export interface WaStatus {
  id: string;
  status: string;
  timestamp?: string;
  recipient_id?: string;
  errors?: { code?: number; title?: string; message?: string; error_data?: { details?: string } }[];
}

export interface WaInbound {
  id: string;
  from: string;
  timestamp?: string;
  type: string;
  text?: { body?: string };
  button?: { text?: string };
  interactive?: { button_reply?: { id?: string; title?: string }; list_reply?: { id?: string; title?: string } };
  image?: { caption?: string };
  video?: { caption?: string };
  document?: { caption?: string; filename?: string };
  reaction?: { emoji?: string };
  context?: { id?: string };
}

export interface WaContact {
  wa_id?: string;
  profile?: { name?: string };
}

const at = (ts: string | undefined) => {
  const n = Number(ts);
  return Number.isFinite(n) && n > 0 ? new Date(n * 1000) : new Date();
};

export async function applyStatus(s: WaStatus): Promise<void> {
  if (!s.id) return;
  const when = at(s.timestamp);
  const where = { waMessageId: s.id, direction: 'OUT' };
  if (s.status === 'delivered') {
    await prismaUnscoped.whatsAppMessage.updateMany({ where: { ...where, status: 'sent' }, data: { status: 'delivered', deliveredAt: when } });
  } else if (s.status === 'read') {
    await prismaUnscoped.whatsAppMessage.updateMany({ where: { ...where, status: { in: ['sent', 'delivered'] } }, data: { status: 'read', readAt: when } });
    // Read implies delivered, even if that receipt has not arrived.
    await prismaUnscoped.whatsAppMessage.updateMany({ where: { ...where, deliveredAt: null }, data: { deliveredAt: when } });
  } else if (s.status === 'failed') {
    const e = s.errors?.[0];
    const error = e ? `${e.code ?? ''}${e.code ? ': ' : ''}${e.error_data?.details || e.message || e.title || 'Not delivered'}`.slice(0, 300) : 'Not delivered';
    await prismaUnscoped.whatsAppMessage.updateMany({ where: { ...where, status: { not: 'read' } }, data: { status: 'failed', failedAt: when, error } });
  }
  // "sent" adds nothing: the row starts as sent.
}

function textOf(m: WaInbound): string {
  switch (m.type) {
    case 'text':
      return m.text?.body ?? '';
    case 'button':
      return m.button?.text ?? '';
    case 'interactive':
      return m.interactive?.button_reply?.title ?? m.interactive?.list_reply?.title ?? '';
    case 'reaction':
      return m.reaction?.emoji ? `Reacted ${m.reaction.emoji}` : 'Reacted';
    case 'image':
    case 'video':
      return m[m.type]?.caption || `[${m.type}]`;
    case 'document':
      return m.document?.caption || (m.document?.filename ? `[document] ${m.document.filename}` : '[document]');
    default:
      return `[${m.type}]`;
  }
}

const last10 = (digits: string) => digits.slice(-10);

/** Who the reply belongs to — see the order in the header. */
async function match(phone: string, replyToWaId: string | null): Promise<{ tenantId: string | null; userId: string | null; crmContactId: string | null }> {
  const quoted = replyToWaId ? await prismaUnscoped.whatsAppMessage.findUnique({ where: { waMessageId: replyToWaId }, select: { tenantId: true, userId: true, crmContactId: true } }) : null;
  const recent =
    quoted ??
    (await prismaUnscoped.whatsAppMessage.findFirst({
      where: { phone, direction: 'OUT', createdAt: { gte: new Date(Date.now() - RECENT_DAYS * DAY) } },
      orderBy: { createdAt: 'desc' },
      select: { tenantId: true, userId: true, crmContactId: true },
    }));
  if (recent && (recent.tenantId || recent.crmContactId)) return recent;

  const key = last10(phone);
  if (key.length === 10) {
    const contact = await prismaUnscoped.crmContact.findFirst({
      where: { deletedAt: null, OR: [{ phoneKey: key }, { whatsapp: { endsWith: key } }] },
      orderBy: { updatedAt: 'desc' },
      select: { id: true },
    });
    if (contact) return { tenantId: null, userId: null, crmContactId: contact.id };

    // Phones are stored as typed ("+91 98260 10000"), so compare digits only.
    const users = await prismaUnscoped.$queryRaw<{ id: string; tenantId: string }[]>`
      SELECT "id", "tenantId" FROM "User"
      WHERE "tenantId" IS NOT NULL AND "role" IN ('STUDENT', 'GUARDIAN') AND "phone" IS NOT NULL
        AND right(regexp_replace("phone", '[^0-9]', '', 'g'), 10) = ${key}
      LIMIT 5`;
    const tenants = new Set(users.map((u) => u.tenantId));
    if (tenants.size === 1) return { tenantId: users[0].tenantId, userId: users.length === 1 ? users[0].id : null, crmContactId: null };
  }
  return { tenantId: null, userId: null, crmContactId: null };
}

export async function saveInbound(m: WaInbound, contacts: WaContact[] | undefined): Promise<void> {
  if (!m.id || !m.from) return;
  const phone = m.from.replace(/\D/g, '');
  const profileName = contacts?.find((c) => c.wa_id === m.from)?.profile?.name?.slice(0, 120) ?? null;
  const replyToWaId = m.context?.id ?? null;
  const body = textOf(m).slice(0, 4000);
  // Meta redelivers until it gets a 200: an id already kept is a no-op.
  if (await prismaUnscoped.whatsAppMessage.findUnique({ where: { waMessageId: m.id }, select: { id: true } })) return;
  const who = await match(phone, replyToWaId);
  try {
    await prismaUnscoped.whatsAppMessage.create({
      data: { ...who, direction: 'IN', waMessageId: m.id, phone, profileName, kind: m.type, body, status: 'received', replyToWaId, createdAt: at(m.timestamp) },
    });
  } catch (err) {
    // Two deliveries racing: the unique message id lets one through.
    if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') return;
    throw err;
  }
  if (who.crmContactId) {
    await onCrmTimeline(who.crmContactId, m.id, phone, profileName, m.type, body);
    // STOP / START (L6): every automatic message stops, or starts again.
    if (await onWhatsAppKeyword(who.crmContactId, body, profileName)) return;
    // A tap on one of our three buttons (L4) gets its answer.
    const buttonId = m.interactive?.button_reply?.id;
    if (m.type === 'interactive' && buttonId?.startsWith('HC_')) await onWhatsAppButton(who.crmContactId, buttonId);
  } else if (!who.tenantId) {
    // Nobody we know (L4): a new sales lead with the three-button reply.
    await leadFromWhatsApp({ phone, profileName, body, waMessageId: m.id });
  }
}

async function onCrmTimeline(contactId: string, waMessageId: string, phone: string, profileName: string | null, kind: string, body: string) {
  const c = await prismaUnscoped.crmContact.findUnique({ where: { id: contactId }, select: { firstName: true, lastName: true, ownerId: true } });
  if (!c) return;
  const name = fullName(c);
  await prismaUnscoped.crmActivity.create({
    data: { contactId, type: CrmActivityType.WHATSAPP_IN, body, meta: { waMessageId, phone, profileName, kind }, actorId: null, actorName: profileName || name },
  });
  // Into the owner's batched activity email, like any other change.
  notify({ actor: { id: 'whatsapp', name, email: '' }, text: `${name} sent a WhatsApp message: "${body.slice(0, 100)}${body.length > 100 ? '…' : ''}"`, url: crmUrl(`contacts/${contactId}`), about: [c.ownerId] });
}
