import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, NotFoundError, TooManyRequestsError } from '../../lib/errors';
import { sendWhatsAppTemplate } from '../../lib/whatsapp';
import { inBackground } from '../notifications/notifications.service';
import { audienceMembers, type Audience } from './audience';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * WhatsApp broadcasts (Sprint 4, TEPL): one message to everyone in an
 * audience — a block, floor, shift or department. With a Meta-approved
 * template name it goes as that template ({{1}} is the employee's name);
 * without one it goes as text, which Meta delivers only inside an open
 * conversation. Sent one by one in the background, with the counts kept on
 * the broadcast; each message is also in the WhatsApp message list.
 */

const PAUSE_MS = 120; // well inside Meta's per-number rate

export async function preview(a: Audience) {
  const members = await audienceMembers(getTenantIdOrThrow(), a);
  return { total: members.length, withPhone: members.filter((m) => !!m.phone).length, sample: members.slice(0, 5).map((m) => m.name) };
}

/** The text one person gets: {name} becomes their name. */
const personalise = (body: string, name: string) => body.replace(/\{name\}/g, name.split(' ')[0] || name);

const BROADCASTS_PER_HOUR = 5;

export async function createBroadcast(input: { title: string; body: string; templateName?: string | null; audience: Audience }, actorId: string) {
  const tenantId = getTenantIdOrThrow();
  // Sprint 7 hardening: each one goes from the company's number to thousands, so a few an hour at most.
  const lastHour = await db.whatsAppBroadcast.count({ where: { createdAt: { gte: new Date(Date.now() - 3_600_000) } } });
  if (lastHour >= BROADCASTS_PER_HOUR) throw new TooManyRequestsError(`At most ${BROADCASTS_PER_HOUR} broadcasts an hour — wait a little before the next`);
  const members = await audienceMembers(tenantId, input.audience);
  const reachable = members.filter((m) => !!m.phone);
  if (!reachable.length) throw new BadRequestError('Nobody in that audience has a phone number');
  const b = await db.whatsAppBroadcast.create({
    data: { tenantId, title: input.title, body: input.body, templateName: input.templateName || null, audience: { ...input.audience }, total: reachable.length, createdById: actorId },
  });
  inBackground('whatsapp: broadcast', () => send(tenantId, b.id, reachable));
  return b;
}

async function send(tenantId: string, id: string, people: { userId: string; name: string; phone: string | null }[]) {
  const b = await prismaUnscoped.whatsAppBroadcast.update({ where: { id }, data: { status: 'SENDING' } });
  let sent = 0;
  let failed = 0;
  for (const [i, p] of people.entries()) {
    const text = personalise(b.body, p.name);
    const r = await sendWhatsAppTemplate(p.phone!, b.templateName ?? undefined, [p.name], text, { tenantId, userId: p.userId, purpose: 'BROADCAST' }).catch(() => ({ sent: false, mode: 'error' as const }));
    // Dry-run (no WhatsApp configured) counts as sent, as the reminders do.
    if (r.sent || r.mode === 'log') sent++;
    else failed++;
    if (i % 20 === 19) await prismaUnscoped.whatsAppBroadcast.update({ where: { id }, data: { sent, failed } });
    await new Promise((res) => setTimeout(res, PAUSE_MS));
  }
  await prismaUnscoped.whatsAppBroadcast.update({ where: { id }, data: { sent, failed, status: 'DONE', finishedAt: new Date() } });
}

export function listBroadcasts() {
  return db.whatsAppBroadcast.findMany({ orderBy: { createdAt: 'desc' }, take: 50 });
}

/** Every broadcast a page at a time (Sprint L3), newest first; only the newest 50 could be seen before. */
export async function pageBroadcasts(pagination: Pagination) {
  const [rows, total] = await Promise.all([
    db.whatsAppBroadcast.findMany({ orderBy: [{ createdAt: 'desc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.whatsAppBroadcast.count(),
  ]);
  return paginated(rows, total, pagination);
}

export async function getBroadcast(id: string) {
  const b = await db.whatsAppBroadcast.findFirst({ where: { id } });
  if (!b) throw new NotFoundError('Broadcast not found');
  return b;
}
