import { env } from '../config/env';
import { prismaUnscoped } from './prisma';
import { getTenantContext } from './tenantContext';

/**
 * Provider-agnostic WhatsApp sender.
 *
 * Default is "log" mode — a dry run that records the message but sends nothing,
 * so the product is fully usable before a WhatsApp Business account is approved.
 * Set WHATSAPP_PROVIDER=meta with a token + phone-number id to go live via the
 * Meta Cloud API (swap in an aggregator adapter here if you pick Gupshup/MSG91).
 */
export function isWhatsAppConfigured(): boolean {
  return env.WHATSAPP_PROVIDER === 'meta' && !!env.WHATSAPP_API_TOKEN && !!env.WHATSAPP_PHONE_NUMBER_ID;
}

export interface SendResult {
  sent: boolean;
  mode: 'meta' | 'log' | 'meta-error';
}

/**
 * Who a message is for, so the row recorded for it (and the delivery
 * receipts and replies that follow) belong to the right hostel and student.
 * tenantId defaults to the request's tenant; pass it from background jobs.
 */
export interface WhatsAppContext {
  tenantId?: string | null;
  userId?: string | null;
  purpose?: 'FEE_REMINDER' | 'PAYMENT_LINK' | 'RENT_REMINDER' | 'BROADCAST' | 'LEAD_ALERT' | 'LEAD_OVERDUE' | 'DEMO' | 'LEAD_FIRST' | 'LEAD_NO_ANSWER' | 'LEAD_REPLY' | 'REQUEST_CLOSED';
  /** A CRM contact (platform-level): replies then land on their timeline. */
  crmContactId?: string | null;
}

type Payload = { type: 'text'; text: { body: string } } | { type: 'template'; template: Record<string, unknown> } | { type: 'interactive'; interactive: Record<string, unknown> };

/** POST one message to the Cloud API; Meta's message id on success, its error text otherwise. */
async function post(to: string, payload: Payload): Promise<{ ok: true; id: string | null } | { ok: false; error: string }> {
  try {
    const res = await fetch(`${env.WHATSAPP_API_BASE}/${env.WHATSAPP_PHONE_NUMBER_ID}/messages`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${env.WHATSAPP_API_TOKEN}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ messaging_product: 'whatsapp', to, ...payload }),
    });
    const body = (await res.json().catch(() => null)) as { messages?: { id?: string }[]; error?: { code?: number; message?: string } } | null;
    if (!res.ok) {
      const error = body?.error ? `${body.error.code ?? res.status}: ${body.error.message ?? 'refused'}` : `HTTP ${res.status}`;
      // eslint-disable-next-line no-console
      console.error(`WhatsApp ${payload.type} send failed (${error}) to ${to}`);
      return { ok: false, error: error.slice(0, 300) };
    }
    return { ok: true, id: body?.messages?.[0]?.id ?? null };
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`WhatsApp ${payload.type} send error:`, err);
    return { ok: false, error: (err instanceof Error ? err.message : String(err)).slice(0, 300) };
  }
}

/** Keep a row for a real send. Never fails the send itself. */
async function record(to: string, kind: 'text' | 'template' | 'interactive', body: string, ctx: WhatsAppContext | undefined, r: Awaited<ReturnType<typeof post>>) {
  try {
    await prismaUnscoped.whatsAppMessage.create({
      data: {
        tenantId: ctx?.tenantId !== undefined ? ctx.tenantId : getTenantContext()?.tenantId ?? null,
        direction: 'OUT',
        crmContactId: ctx?.crmContactId ?? null,
        waMessageId: r.ok ? r.id : null,
        phone: to,
        userId: ctx?.userId ?? null,
        kind,
        body: body.slice(0, 4000),
        purpose: ctx?.purpose ?? null,
        status: r.ok ? 'sent' : 'failed',
        error: r.ok ? null : r.error,
        failedAt: r.ok ? null : new Date(),
      },
    });
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error('WhatsApp message not recorded:', err instanceof Error ? err.message : err);
  }
}

export async function sendWhatsApp(toPhone: string, text: string, ctx?: WhatsAppContext): Promise<SendResult> {
  if (isWhatsAppConfigured()) {
    const to = waPhone(toPhone);
    const r = await post(to, { type: 'text', text: { body: text } });
    await record(to, 'text', text, ctx, r);
    return r.ok ? { sent: true, mode: 'meta' } : { sent: false, mode: 'meta-error' };
  }

  // Dry-run: log and report not-sent so callers can surface "would have sent N".
  // eslint-disable-next-line no-console
  console.log(`[whatsapp:log] → ${toPhone}: ${text}`);
  return { sent: false, mode: 'log' };
}

/**
 * A Meta-approved template message — the only kind Meta delivers to a
 * number with no open conversation, which is every reminder. `params` fill
 * the template's {{1}}, {{2}}… body placeholders in order. Falls back to a
 * plain text message when no template is configured.
 */
export async function sendWhatsAppTemplate(toPhone: string, templateName: string | undefined, params: string[], fallbackText: string, ctx?: WhatsAppContext): Promise<SendResult> {
  if (!templateName || !isWhatsAppConfigured()) return sendWhatsApp(toPhone, fallbackText, ctx);
  const to = waPhone(toPhone);
  const r = await post(to, {
    type: 'template',
    template: {
      name: templateName,
      language: { code: env.WHATSAPP_TEMPLATE_LANG },
      components: [{ type: 'body', parameters: params.map((text) => ({ type: 'text', text })) }],
    },
  });
  // The fallback text says what the template said, for the message list.
  await record(to, 'template', fallbackText, ctx, r);
  return r.ok ? { sent: true, mode: 'meta' } : { sent: false, mode: 'meta-error' };
}

/**
 * A message with up to three reply buttons (L4: the reply to a new number).
 * Free-form, so it only reaches someone who wrote to us in the last 24 hours.
 * Dry-run mode logs it, like every other send.
 */
export async function sendWhatsAppButtons(toPhone: string, body: string, buttons: { id: string; title: string }[], ctx?: WhatsAppContext): Promise<SendResult> {
  const fallback = `${body}\n${buttons.map((b) => `• ${b.title}`).join('\n')}`;
  if (!isWhatsAppConfigured()) {
    // eslint-disable-next-line no-console
    console.log(`[whatsapp:log] → ${toPhone}: ${fallback}`);
    return { sent: false, mode: 'log' };
  }
  const to = waPhone(toPhone);
  const r = await post(to, {
    type: 'interactive',
    interactive: { type: 'button', body: { text: body }, action: { buttons: buttons.slice(0, 3).map((b) => ({ type: 'reply', reply: { id: b.id, title: b.title.slice(0, 20) } })) } },
  });
  await record(to, 'interactive', fallback, ctx, r);
  return r.ok ? { sent: true, mode: 'meta' } : { sent: false, mode: 'meta-error' };
}

/** Strip spaces/dashes; assume Indian numbers get a 91 country code if 10 digits. */
export function waPhone(phone: string): string {
  const digits = phone.replace(/\D/g, '');
  return digits.length === 10 ? `91${digits}` : digits;
}
