import { Role, SubscriptionStatus, TenantAccessKind, TenantStatus } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { sendEmail, emailFailed } from '../../lib/email';
import { isPlaceholderEmail } from '../../lib/no-login';
import { crmEmail, planExpiryReminderEmail, type CrmEmailItem } from '../../lib/email-templates';
import { publicWebUrl } from '../../config/env';
import { buyerParty, sellerParty } from '../subscriptions/subscriptions.service';
import { getSettings } from './platform.service';
import { suspendExpired } from '../tenants/tenant-access.service';
import { tenantHasFeature } from '../../middleware/requireFeature';

/**
 * Plan expiry reminders (9 Oct 2026).
 *
 * A paying hostel's plan "ends" on the last day of its latest fully paid
 * subscription invoice period — the paid-until date. From 09:00 India time on
 * the days that are 10, 5 and 1 days before it (the super admin can change
 * the days or switch it off), the hostel's billing email and first admin get
 * one reminder each; if a renewal invoice is waiting, the reminder names it.
 * Paying the renewal moves the paid-until date, so the reminders stop and a
 * new set is due before the new date.
 *
 * Every Monday from 09:00 the super admins get a summary: what ends in the
 * next two weeks, what has lapsed in the last month, and paying hostels with
 * no paid period on record (which therefore get no reminders).
 *
 * PlanReminderLog's unique key makes each email go once, however often the
 * hourly tick runs and on however many servers. Background work: unscoped
 * client, tenant ids carried explicitly.
 */

const DAY = 86_400_000;
const IST_MS = 330 * 60_000;
const SEND_HOUR = 9;

/** The India date (YYYY-MM-DD), hour and weekday (0 = Sunday) of an instant. */
function ist(now: Date) {
  const s = new Date(now.getTime() + IST_MS);
  return { date: s.toISOString().slice(0, 10), hour: s.getUTCHours(), weekday: s.getUTCDay() };
}

const daysBetween = (fromDate: string, toDate: string) => Math.round((Date.parse(`${toDate}T00:00:00Z`) - Date.parse(`${fromDate}T00:00:00Z`)) / DAY);
const fmtDate = (d: string) => new Date(`${d}T12:00:00Z`).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' });
const fmtDay = (d: Date | null) => (d ? fmtDate(d.toISOString().slice(0, 10)) : null);
const rupees = (n: number) => `₹${n.toLocaleString('en-IN')}`;
const adminUrl = (hash: string) => `${publicWebUrl}/#${hash}`;

export interface PlanExpiry {
  tenantId: string;
  name: string;
  planName: string;
  monthlyPrice: number;
  /** Last paid-for day, YYYY-MM-DD; null when no paid invoice has a period end. */
  paidUntil: string | null;
  /** Days from today (India) to paidUntil; negative once it has passed. */
  daysLeft: number | null;
  renewal: { id: string; number: string; balance: number; dueDate: string | null } | null;
  /** TRIAL or PLAN; null for an older hostel without an access window. */
  accessKind: TenantAccessKind | null;
}

/**
 * Every active hostel with an end date: its access end date (trial or plan,
 * 10 Oct 2026), or — for a paying hostel without one — the end of its latest
 * paid invoice period. Plus any renewal invoice waiting.
 */
export async function planExpiries(now = new Date()): Promise<PlanExpiry[]> {
  const today = ist(now).date;
  const tenants = await prismaUnscoped.tenant.findMany({
    where: { status: TenantStatus.ACTIVE, OR: [{ accessEndsOn: { not: null } }, { planRef: { monthlyPrice: { gt: 0 } } }] },
    select: { id: true, name: true, accessKind: true, accessEndsOn: true, planRef: { select: { name: true, monthlyPrice: true } } },
    orderBy: { name: 'asc' },
  });
  if (!tenants.length) return [];
  const ids = tenants.map((t) => t.id);
  const [paid, open] = await Promise.all([
    prismaUnscoped.subscriptionInvoice.groupBy({ by: ['tenantId'], where: { tenantId: { in: ids }, status: SubscriptionStatus.PAID, periodEnd: { not: null } }, _max: { periodEnd: true } }),
    prismaUnscoped.subscriptionInvoice.findMany({
      where: { tenantId: { in: ids }, status: { in: [SubscriptionStatus.PENDING, SubscriptionStatus.PARTIAL] } },
      select: { id: true, tenantId: true, invoiceNumber: true, amount: true, dueDate: true, periodEnd: true, issueDate: true, payments: { select: { amount: true } } },
      orderBy: [{ issueDate: 'desc' }, { createdAt: 'desc' }],
    }),
  ]);
  return tenants.map((t) => {
    const end = t.accessEndsOn ?? paid.find((p) => p.tenantId === t.id)?._max.periodEnd ?? null;
    const paidUntil = end ? end.toISOString().slice(0, 10) : null;
    // The renewal: an unpaid invoice covering time after the paid-until date
    // (or, without a period, the newest unpaid one).
    const mine = open.filter((i) => i.tenantId === t.id);
    const r = mine.find((i) => (paidUntil && i.periodEnd ? i.periodEnd.toISOString().slice(0, 10) > paidUntil : !i.periodEnd)) ?? null;
    return {
      tenantId: t.id,
      name: t.name,
      planName: t.accessKind === TenantAccessKind.TRIAL ? 'Free trial' : t.planRef?.name ?? 'No plan',
      monthlyPrice: t.planRef?.monthlyPrice ?? 0,
      accessKind: t.accessKind,
      paidUntil,
      daysLeft: paidUntil ? daysBetween(today, paidUntil) : null,
      renewal: r ? { id: r.id, number: r.invoiceNumber ?? 'pending invoice', balance: Math.max(0, r.amount - r.payments.reduce((n, p) => n + p.amount, 0)), dueDate: fmtDay(r.dueDate) } : null,
    };
  });
}

/** Log first (the unique key is the once-only guard), then send, then record how it went. */
async function sendOnce(p: { key: string; kind: 'EXPIRY' | 'WEEKLY_SUMMARY'; to: string; subject: string; text: string; html: string; tenantId?: string; daysBefore?: number; expiresOn?: string }) {
  // The key is a once-only guard. `create()` followed by a caught P2002 still
  // makes Prisma log an error on every scheduler retry; createMany with
  // skipDuplicates keeps the same atomic idempotency without noisy logs.
  const inserted = await prismaUnscoped.planReminderLog.createMany({
    data: { key: p.key, kind: p.kind, toEmail: p.to, subject: p.subject.slice(0, 300), tenantId: p.tenantId ?? null, daysBefore: p.daysBefore ?? null, expiresOn: p.expiresOn ?? null },
    skipDuplicates: true,
  });
  if (inserted.count === 0) return 'DUPLICATE' as const;
  const r = await sendEmail(p.to, p.subject, p.text, p.html);
  const status = r.mode === 'log' ? 'DRY_RUN' : emailFailed(r) ? 'FAILED' : 'SENT';
  await prismaUnscoped.planReminderLog.update({ where: { key: p.key }, data: { status, ...(status === 'FAILED' ? { error: r.mode } : {}) } });
  return status;
}

export interface PlanReminderRun {
  suspended: number;
  reminders: number;
  summaries: number;
}

/** The hourly pass. `now` is movable for the test clock. */
export async function runPlanReminders(now = new Date()): Promise<PlanReminderRun> {
  // Hostels whose last day has passed are paused first, at any hour.
  const run: PlanReminderRun = { suspended: await suspendExpired(now), reminders: 0, summaries: 0 };
  const settings = await getSettings();
  const { date, hour, weekday } = ist(now);
  if (hour < SEND_HOUR || (!settings.planRemindersEnabled && !settings.planWeeklySummary)) return run;
  const all = await planExpiries(now);

  // 1. Reminders to hostels.
  const offsets = new Set(settings.planReminderDays.filter((d) => d >= 0 && d <= 60));
  if (settings.planRemindersEnabled && offsets.size) {
    const seller = await sellerParty();
    // Self-serve trials linked to the CRM get the CRM's trial nudges instead (L5), not a second set of emails.
    const linked = new Set((await prismaUnscoped.crmContact.findMany({ where: { tenantId: { not: null }, deletedAt: null }, select: { tenantId: true } })).map((c) => c.tenantId));
    for (const t of all) {
      if (t.daysLeft === null || !offsets.has(t.daysLeft)) continue;
      if (t.accessKind === TenantAccessKind.TRIAL && linked.has(t.tenantId) && (await getCrmTrialNudgesOn())) continue;
      const buyer = await buyerParty(t.tenantId);
      const mail = planExpiryReminderEmail({ seller, hostelName: t.name, planName: t.planName, endsOn: fmtDate(t.paidUntil!), daysLeft: t.daysLeft, renewal: (await tenantHasFeature(t.tenantId, 'billing')) ? t.renewal : null, trial: t.accessKind === TenantAccessKind.TRIAL });
      for (const to of buyer.recipients) {
        const s = await sendOnce({ key: `plan-expiry:${t.tenantId}:${t.paidUntil}:${t.daysLeft}:${to.toLowerCase()}`, kind: 'EXPIRY', to, ...mail, tenantId: t.tenantId, daysBefore: t.daysLeft, expiresOn: t.paidUntil! });
        if (s === 'SENT' || s === 'DRY_RUN') run.reminders++;
      }
    }
  }

  // 2. Monday: the super admins' summary.
  if (settings.planWeeklySummary && weekday === 1) {
    const admins = await prismaUnscoped.user.findMany({ where: { role: Role.SUPER_ADMIN, deactivatedAt: null }, select: { email: true } });
    const to = admins.map((a) => a.email).filter((e) => !isPlaceholderEmail(e));
    if (to.length) {
      const paused = await prismaUnscoped.tenant.findMany({ where: { status: TenantStatus.SUSPENDED, suspendedCause: 'EXPIRED' }, select: { id: true, name: true, suspendedReason: true }, orderBy: { suspendedAt: 'desc' }, take: 20 });
      const mail = weeklySummary(all, await sentLastWeek(now), settings.planRemindersEnabled, paused);
      for (const addr of to) {
        const s = await sendOnce({ key: `plan-summary:${date}:${addr.toLowerCase()}`, kind: 'WEEKLY_SUMMARY', to: addr, ...mail });
        if (s === 'SENT' || s === 'DRY_RUN') run.summaries++;
      }
    }
  }
  return run;
}

async function sentLastWeek(now: Date) {
  return prismaUnscoped.planReminderLog.count({ where: { kind: 'EXPIRY', status: { in: ['SENT', 'DRY_RUN'] }, createdAt: { gte: new Date(now.getTime() - 7 * DAY), lte: now } } });
}

function weeklySummary(all: PlanExpiry[], sent: number, remindersOn: boolean, paused: { id: string; name: string; suspendedReason: string | null }[]) {
  const soon = all.filter((t) => t.daysLeft !== null && t.daysLeft >= 0 && t.daysLeft <= 14).sort((a, b) => a.daysLeft! - b.daysLeft!);
  const lapsed = all.filter((t) => t.daysLeft !== null && t.daysLeft < 0 && t.daysLeft >= -30).sort((a, b) => b.daysLeft! - a.daysLeft!);
  const unknown = all.filter((t) => t.paidUntil === null);
  const line = (t: PlanExpiry, lapsedRow = false): CrmEmailItem => ({
    text: t.name,
    sub: [t.accessKind === TenantAccessKind.TRIAL ? 'Free trial' : `${t.planName} · ${rupees(t.monthlyPrice)}/month`, t.renewal ? `Renewal ${t.renewal.number}: ${rupees(t.renewal.balance)} due${t.renewal.dueDate ? ` by ${t.renewal.dueDate}` : ''}` : 'No renewal invoice yet'].join(' · '),
    url: adminUrl(`tenants/${t.tenantId}`),
    aside: lapsedRow ? `Ended ${fmtDate(t.paidUntil!)}` : t.daysLeft === 0 ? `Ends today` : `${t.daysLeft} day${t.daysLeft === 1 ? '' : 's'} · ${fmtDate(t.paidUntil!)}`,
    tone: lapsedRow || (t.daysLeft !== null && t.daysLeft <= 1) ? 'warning' : null,
  });
  const title = soon.length ? `${soon.length} plan${soon.length === 1 ? '' : 's'} end in the next 2 weeks` : 'No plans end in the next 2 weeks';
  return crmEmail({
    title: `Plans: ${title.charAt(0).toLowerCase()}${title.slice(1)}`,
    intro: `Paying hostels whose paid-until date is close or has passed. ${remindersOn ? 'Hostels are reminded automatically before their date.' : 'Automatic reminders to hostels are switched off.'}`,
    badge: 'Weekly summary',
    figures: [
      ['Ending in 14 days', String(soon.length)],
      ['Lapsed (30 days)', String(lapsed.length)],
      ['Reminders sent', String(sent)],
    ],
    sections: [
      { heading: 'Ending in the next 2 weeks', items: soon.map((t) => line(t)), empty: 'Nothing ends in the next two weeks.' },
      { heading: 'Lapsed in the last 30 days, not renewed', items: lapsed.map((t) => line(t, true)), empty: 'No plan has lapsed in the last month.' },
      { heading: 'Paused: trial or plan ran out', items: paused.map((p) => ({ text: p.name, sub: p.suspendedReason ?? 'Expired', url: adminUrl(`tenants/${p.id}`), tone: 'warning' as const })), empty: 'No hostel is paused for running out.' },
      ...(unknown.length
        ? [{ heading: 'No paid period on record (no reminders possible)', items: unknown.slice(0, 15).map((t) => ({ text: t.name, sub: `${t.planName} · raise an invoice with a period and record its payment`, url: adminUrl('tenants') })) }]
        : []),
    ],
    cta: { label: 'Open hostels', url: adminUrl('tenants') },
    reason: 'You get this because you are a HostelCare super admin. Turn it off in Settings → Plan expiry reminders.',
    signoff: '— HostelCare',
  });
}

/** For the settings page: what is coming up, and what was sent. */
export async function planReminderOverview(now = new Date()) {
  const [settings, all, recent] = await Promise.all([getSettings(), planExpiries(now), prismaUnscoped.planReminderLog.findMany({ orderBy: { createdAt: 'desc' }, take: 30 })]);
  const names = new Map(all.map((t) => [t.tenantId, t.name]));
  const missing = recent.filter((r) => r.tenantId && !names.has(r.tenantId)).map((r) => r.tenantId!);
  if (missing.length) {
    for (const t of await prismaUnscoped.tenant.findMany({ where: { id: { in: missing } }, select: { id: true, name: true } })) names.set(t.id, t.name);
  }
  return {
    settings: { planRemindersEnabled: settings.planRemindersEnabled, planReminderDays: settings.planReminderDays, planWeeklySummary: settings.planWeeklySummary },
    // Every paying hostel, soonest first; those with no paid period last.
    upcoming: [...all].sort((a, b) => (a.daysLeft ?? 99_999) - (b.daysLeft ?? 99_999)),
    recent: recent.map((r) => ({ id: r.id, kind: r.kind, tenantName: r.tenantId ? names.get(r.tenantId) ?? 'Removed hostel' : null, daysBefore: r.daysBefore, expiresOn: r.expiresOn, toEmail: r.toEmail, subject: r.subject, status: r.status, createdAt: r.createdAt })),
  };
}

/** Whether the CRM's trial nudges are on (L5); when off, linked trials get the plan reminders as before. */
async function getCrmTrialNudgesOn() {
  const s = await prismaUnscoped.crmSettings.findUnique({ where: { id: 'singleton' }, select: { trialNudges: true } });
  return s?.trialNudges ?? true;
}
