import { CrmActivityType, CrmStageKind, PaymentStatus, Prisma, SubscriptionStatus, TenantAccessKind, TenantKind, TenantStatus } from '@prisma/client';
import { env, publicWebUrl } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { crmEmail, customerWelcomeEmail, reviewRequestEmail, trialExtendedEmail, trialNudgeEmail, trialStepLine, type TrialStep } from '../../lib/email-templates';
import { sendWhatsAppTemplate } from '../../lib/whatsapp';
import { extendTrial } from '../tenants/tenant-access.service';
import { getCrmSettings } from './crm-settings.service';
import { crmUrl, deliver } from './crm-mail';
import { addToNurture, fullName, unsubscribeUrl } from './crm-contacts.service';
import { workingDue } from './crm-leads.service';
import { getDeal, moveDeal } from './crm-deals.service';
import { advanceDeal, SYSTEM_ACTOR } from './crm-pipeline.service';
import { stageByKey, STAGE_KEYS } from './crm-stages.service';
import type { Actor } from './crm-users.service';

/**
 * The trial journey (Sprint L5), run by the CRM clock:
 *
 * - Nudges: the owner hears from us on trial days 0, 1, 3, 5 and 6, between
 *   10 am and 8 pm India time, each pointing to their next step (add
 *   students → raise rent → record a payment → keep going); day 6 says the
 *   trial ends tomorrow. A day that passes unsent is skipped, never sent late.
 * - Trial active: the first rent invoice and first payment in the hostel
 *   move the deal on by itself, and sales hears "ready to convert".
 * - Unused trial: one that ends still at "Trial started" closes as Lost,
 *   "Trial not used", and the lead joins Nurture.
 * - Won: the hostel's first paid platform invoice wins the deal (the contact
 *   becomes a customer); a welcome goes out, and a review request on day 30.
 *
 * Only trials linked to a CRM contact (self-serve signups) are run this way.
 */

const DAY = 86_400_000;
const IST_MS = 330 * 60_000;
export const NUDGE_DAYS = [0, 1, 3, 5, 6] as const;
const istDate = (d: Date) => new Date(d.getTime() + IST_MS).toISOString().slice(0, 10);
const istHour = (d: Date) => new Date(d.getTime() + IST_MS).getUTCHours();
const dayDiff = (a: string, b: string) => Math.round((Date.parse(`${a}T00:00:00Z`) - Date.parse(`${b}T00:00:00Z`)) / DAY);
const fmtDay = (iso: string) => new Date(`${iso}T12:00:00Z`).toLocaleDateString('en-IN', { day: 'numeric', month: 'long', timeZone: 'Asia/Kolkata' });
const appUrl = () => `${publicWebUrl}/`;

/** Where a hostel is in its trial: what it has done so far. */
export async function trialProgress(tenantId: string) {
  const [students, invoices, payments, beds] = await Promise.all([
    prismaUnscoped.studentProfile.count({ where: { tenantId } }),
    prismaUnscoped.invoice.count({ where: { tenantId } }),
    prismaUnscoped.payment.count({ where: { tenantId, status: PaymentStatus.CLEARED } }),
    prismaUnscoped.bed.count({ where: { tenantId } }),
  ]);
  const step: TrialStep = !students ? 'students' : !invoices ? 'invoice' : !payments ? 'payment' : 'convert';
  return { students, invoices, payments, beds, step, active: invoices > 0 && payments > 0 };
}

/** Linked trial hostels: on a trial, switched on, with a CRM contact pointing at them. */
async function linkedTrials() {
  const contacts = await prismaUnscoped.crmContact.findMany({ where: { tenantId: { not: null }, deletedAt: null }, select: { id: true, tenantId: true, firstName: true, email: true, phone: true, whatsapp: true, consentWhatsapp: true, optedOutAt: true }, take: 2000 });
  if (!contacts.length) return [];
  const tenants = await prismaUnscoped.tenant.findMany({
    where: { id: { in: contacts.map((c) => c.tenantId!) }, accessKind: TenantAccessKind.TRIAL, status: TenantStatus.ACTIVE, accessStartsOn: { not: null } },
    select: { id: true, name: true, kind: true, createdAt: true, accessStartsOn: true, accessEndsOn: true },
  });
  return tenants.map((t) => ({ tenant: t, contact: contacts.find((c) => c.tenantId === t.id)! }));
}

// ── Nudges ─────────────────────────────────────────────────────────────────

export async function sendTrialNudges(now = new Date()) {
  const s = await getCrmSettings();
  if (!s.trialNudges) return 0;
  const hour = istHour(now);
  if (hour < 10 || hour >= 20) return 0;
  let sent = 0;
  for (const { tenant, contact } of await linkedTrials()) {
    if (contact.optedOutAt) continue; // L6: they said stop
    const day = dayDiff(istDate(now), istDate(tenant.accessStartsOn!));
    if (!(NUDGE_DAYS as readonly number[]).includes(day)) continue;
    // Day 0 waits a couple of hours: the welcome email has just gone.
    if (day === 0 && now.getTime() - tenant.createdAt.getTime() < 2 * 3_600_000) continue;
    const p = await trialProgress(tenant.id);
    try {
      await prismaUnscoped.crmTrialNudge.create({ data: { tenantId: tenant.id, day, step: p.step, channel: 'pending', sentAt: now } });
    } catch (e) {
      if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') continue; // already sent
      throw e;
    }
    const dorm = tenant.kind === TenantKind.DORMITORY;
    const first = contact.firstName.split(/\s+/)[0];
    const endsOn = tenant.accessEndsOn ? fmtDay(istDate(tenant.accessEndsOn)) : 'soon';
    // "Ends tomorrow" only when it does: an extended trial's day 6 is an ordinary nudge.
    const endsIn = tenant.accessEndsOn ? dayDiff(istDate(tenant.accessEndsOn), istDate(now)) : null;
    const last = endsIn === 0 || endsIn === 1;
    const channels: string[] = [];
    const to = contact.email ?? (await prismaUnscoped.user.findFirst({ where: { tenantId: tenant.id, role: 'HOSTEL_ADMIN' }, select: { email: true } }))?.email;
    if (to) {
      const status = await deliver({
        key: `trial-nudge:${tenant.id}:${day}`,
        kind: 'TRIAL_NUDGE',
        to,
        mail: trialNudgeEmail({ unsubscribeUrl: unsubscribeUrl(contact.id), name: first, hostelName: tenant.name, day, endsIn, step: p.step, dorm, endsOn, monthly: p.beds * 20, appUrl: appUrl() }),
        force: true,
      });
      if (status !== 'FAILED' && status !== 'SKIPPED') channels.push('email');
    }
    const phone = contact.whatsapp || contact.phone;
    if (phone && contact.consentWhatsapp && env.WHATSAPP_TEMPLATE_TRIAL_NUDGE) {
      const line = last ? `Your free trial ends ${endsIn === 0 ? 'today' : 'tomorrow'} (${endsOn}). ${trialStepLine(p.step, dorm)}` : trialStepLine(p.step, dorm);
      const r = await sendWhatsAppTemplate(phone, env.WHATSAPP_TEMPLATE_TRIAL_NUDGE, [first, line, appUrl()], line, { tenantId: null, crmContactId: contact.id, purpose: 'LEAD_FIRST' });
      if (r.sent || r.mode === 'log') channels.push('whatsapp');
    }
    await prismaUnscoped.crmTrialNudge.update({ where: { tenantId_day: { tenantId: tenant.id, day } }, data: { channel: channels.join('+') || 'none' } });
    if (channels.length) {
      await prismaUnscoped.crmActivity.create({ data: { contactId: contact.id, type: CrmActivityType.AUTO_MESSAGE, meta: { purpose: 'trial_nudge', day, step: p.step, channel: channels.join('+') }, actorName: SYSTEM_ACTOR.name, createdAt: now } });
      sent++;
    }
  }
  return sent;
}

// ── Stage moves ────────────────────────────────────────────────────────────

/** Deals sitting at a keyed stage, with the hostel they are about. */
async function dealsAt(key: typeof STAGE_KEYS.TRIAL_STARTED | typeof STAGE_KEYS.TRIAL_ACTIVE) {
  const stage = await stageByKey(key);
  if (!stage) return [];
  return prismaUnscoped.crmDeal.findMany({ where: { stageId: stage.id, deletedAt: null, tenantId: { not: null } }, select: { id: true, number: true, title: true, tenantId: true, contactId: true, assigneeId: true, createdAt: true }, take: 500 });
}

/** First rent invoice and first payment: the deal moves to "Trial active" and sales hears it. */
export async function activateTrials(now = new Date()) {
  const s = await getCrmSettings();
  let moved = 0;
  for (const d of await dealsAt(STAGE_KEYS.TRIAL_STARTED)) {
    const p = await trialProgress(d.tenantId!);
    if (!p.active) continue;
    const due = workingDue(now, { ...s, responseMinutes: 60 });
    if (!(await advanceDeal(d.id, STAGE_KEYS.TRIAL_ACTIVE, SYSTEM_ACTOR, { nextStep: 'Ready to convert: send the plan invoice', nextActionAt: due }))) continue;
    moved++;
    await alertReady(d, p);
  }
  return moved;
}

async function alertReady(d: { id: string; title: string; contactId: string | null; assigneeId: string | null }, p: Awaited<ReturnType<typeof trialProgress>>) {
  const to = d.assigneeId ? await prismaUnscoped.user.findFirst({ where: { id: d.assigneeId, deactivatedAt: null }, select: { id: true, email: true, name: true } }) : null;
  if (!to) return;
  const url = crmUrl(`deals/${d.id}`);
  await deliver({
    key: `trial-ready:${d.id}`,
    kind: 'TRIAL_READY',
    to: to.email,
    userId: to.id,
    mail: crmEmail({
      title: `Ready to convert: ${d.title}`,
      intro: `${d.title} raised rent and recorded a payment in their trial. Send the plan invoice (${p.beds} beds × ₹20 = ₹${(p.beds * 20).toLocaleString('en-IN')} a month).`,
      badge: 'Trial active',
      tone: 'good',
      figures: [
        ['Students', String(p.students)],
        ['Invoices', String(p.invoices)],
        ['Payments', String(p.payments)],
      ],
      sections: [],
      cta: { label: 'Open the deal', url },
      reason: 'You are assigned to this deal in the HostelCare CRM.',
    }),
  });
}

/** A trial that ended still at "Trial started" closes as Lost, "Trial not used". */
export async function closeUnusedTrials(now = new Date()) {
  const today = istDate(now);
  const lost = await prismaUnscoped.crmStage.findFirst({ where: { kind: CrmStageKind.LOST } });
  if (!lost) return 0;
  let closed = 0;
  for (const d of await dealsAt(STAGE_KEYS.TRIAL_STARTED)) {
    const t = await prismaUnscoped.tenant.findUnique({ where: { id: d.tenantId! }, select: { accessKind: true, accessEndsOn: true } });
    if (!t || t.accessKind !== TenantAccessKind.TRIAL || !t.accessEndsOn || istDate(t.accessEndsOn) >= today) continue;
    await moveDeal(d.id, { stageId: lost.id, lostReasonCode: 'TRIAL_NOT_USED' }, SYSTEM_ACTOR);
    await prismaUnscoped.crmTask.updateMany({ where: { dealId: d.id, kind: 'TRIAL_CHECKIN', done: false }, data: { done: true, doneAt: now } });
    if (d.contactId) await addToNurture(d.contactId, SYSTEM_ACTOR);
    closed++;
  }
  return closed;
}

/** The hostel's first paid platform invoice wins its open deal. */
export async function winPaidTrials(now = new Date()) {
  const won = await prismaUnscoped.crmStage.findFirst({ where: { kind: CrmStageKind.WON } });
  if (!won) return 0;
  const open = await prismaUnscoped.crmDeal.findMany({ where: { deletedAt: null, tenantId: { not: null }, stage: { kind: CrmStageKind.OPEN } }, select: { id: true, tenantId: true, createdAt: true }, take: 500 });
  let count = 0;
  for (const d of open) {
    const paid = await prismaUnscoped.subscriptionInvoice.findFirst({ where: { tenantId: d.tenantId!, status: SubscriptionStatus.PAID, amount: { gt: 0 }, paidAt: { gte: new Date(d.createdAt.getTime() - DAY) } }, select: { id: true } });
    if (!paid) continue;
    await moveDeal(d.id, { stageId: won.id }, SYSTEM_ACTOR);
    await prismaUnscoped.crmTask.updateMany({ where: { dealId: d.id, kind: { in: ['TRIAL_CHECKIN', 'NO_ANSWER_RETRY'] }, done: false }, data: { done: true, doneAt: now } });
    count++;
  }
  return count;
}

/** Welcome a new customer once, and ask for a review on day 30. */
export async function customerMessages(now = new Date()) {
  let sent = 0;
  const won = await prismaUnscoped.crmDeal.findMany({
    where: { deletedAt: null, tenantId: { not: null }, stage: { kind: CrmStageKind.WON }, wonAt: { gte: new Date(now.getTime() - 60 * DAY) }, OR: [{ welcomeSentAt: null }, { reviewAskedAt: null }] },
    include: { contact: { select: { id: true, firstName: true, email: true, optedOutAt: true } } },
    take: 200,
  });
  for (const d of won) {
    if (!d.contact?.email || d.contact.optedOutAt) continue;
    const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: d.tenantId! }, select: { name: true } });
    const hostelName = tenant?.name ?? d.title;
    const first = d.contact.firstName.split(/\s+/)[0];
    if (!d.welcomeSentAt && d.wonAt && now.getTime() - d.wonAt.getTime() < 7 * DAY) {
      const claim = await prismaUnscoped.crmDeal.updateMany({ where: { id: d.id, welcomeSentAt: null }, data: { welcomeSentAt: now } });
      if (claim.count) {
        await deliver({ key: `welcome:${d.id}`, kind: 'CUSTOMER_WELCOME', to: d.contact.email, mail: customerWelcomeEmail({ name: first, hostelName, appUrl: appUrl(), unsubscribeUrl: unsubscribeUrl(d.contact.id) }), force: true });
        await prismaUnscoped.crmActivity.create({ data: { contactId: d.contact.id, dealId: d.id, type: CrmActivityType.AUTO_MESSAGE, meta: { purpose: 'welcome', channel: 'email' }, actorName: SYSTEM_ACTOR.name, createdAt: now } });
        sent++;
      }
    }
    if (!d.reviewAskedAt && d.wonAt && now.getTime() - d.wonAt.getTime() >= 30 * DAY) {
      const claim = await prismaUnscoped.crmDeal.updateMany({ where: { id: d.id, reviewAskedAt: null }, data: { reviewAskedAt: now } });
      if (claim.count) {
        await deliver({ key: `review:${d.id}`, kind: 'CUSTOMER_REVIEW', to: d.contact.email, mail: reviewRequestEmail({ name: first, hostelName, reviewUrl: env.GOOGLE_REVIEW_URL ?? null, unsubscribeUrl: unsubscribeUrl(d.contact.id) }), force: true });
        await prismaUnscoped.crmActivity.create({ data: { contactId: d.contact.id, dealId: d.id, type: CrmActivityType.AUTO_MESSAGE, meta: { purpose: 'review', channel: 'email' }, actorName: SYSTEM_ACTOR.name, createdAt: now } });
        sent++;
      }
    }
  }
  return sent;
}

/** Everything above, in order, for the CRM clock. */
export async function trialJourneyTick(now = new Date()) {
  const won = await winPaidTrials(now);
  const activated = await activateTrials(now);
  const unused = await closeUnusedTrials(now);
  const nudges = await sendTrialNudges(now);
  const customer = await customerMessages(now);
  return { won, activated, unused, nudges, customer };
}

// ── The one extension ──────────────────────────────────────────────────────

/** Sales gives an active trial (rent collected, not yet paid) one 7-day extension. */
export async function extendTrialFromCrm(dealId: string, actor: Actor, now = new Date()) {
  const d = await prismaUnscoped.crmDeal.findFirst({ where: { id: dealId, deletedAt: null }, include: { stage: true, contact: { select: { id: true, firstName: true, lastName: true, email: true } } } });
  if (!d) throw new NotFoundError('Deal not found');
  if (!d.tenantId) throw new BadRequestError('This deal has no hostel account.', 'NO_HOSTEL_ACCOUNT');
  if (d.stage.key !== STAGE_KEYS.TRIAL_ACTIVE) throw new BadRequestError('Only an active trial (rent raised and collected) can be extended.', 'TRIAL_NOT_ACTIVE');
  if (d.trialExtendedAt) throw new ConflictError('This trial has already been extended once.', 'ALREADY_EXTENDED');
  const claim = await prismaUnscoped.crmDeal.updateMany({ where: { id: d.id, trialExtendedAt: null }, data: { trialExtendedAt: now } });
  if (!claim.count) throw new ConflictError('This trial has already been extended once.', 'ALREADY_EXTENDED');
  let endsOn: string | null;
  try {
    const r = await extendTrial(d.tenantId, 7, now);
    endsOn = r.access.endsOn;
  } catch (e) {
    await prismaUnscoped.crmDeal.update({ where: { id: d.id }, data: { trialExtendedAt: null } });
    throw e;
  }
  const when = endsOn ? fmtDay(endsOn) : 'a week from now';
  await prismaUnscoped.crmActivity.create({ data: { dealId: d.id, contactId: d.contactId, type: CrmActivityType.NOTE, body: `Free trial extended by 7 days, to ${when}.`, actorId: actor.id, actorName: actor.name, createdAt: now } });
  if (d.contact?.email) {
    const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: d.tenantId }, select: { name: true } });
    await deliver({ key: `trial-extended:${d.id}`, kind: 'TRIAL_EXTENDED', to: d.contact.email, mail: trialExtendedEmail({ name: d.contact.firstName.split(/\s+/)[0], hostelName: tenant?.name ?? d.title, endsOn: when, appUrl: appUrl(), unsubscribeUrl: unsubscribeUrl(d.contact.id) }), force: true });
  }
  return { deal: await getDeal(d.id), endsOn, contactName: d.contact ? fullName(d.contact) : null };
}
