import { InvoiceStatus } from '@prisma/client';
import { invoiceKindWord, isDormitoryTenant } from '../../lib/invoice-words';
import { prismaUnscoped } from '../../lib/prisma';
import { sendEmail, isEmailConfigured } from '../../lib/email';
import { brandFromSettings } from '../../lib/email-brand';
import { sendWhatsApp, sendWhatsAppTemplate, isWhatsAppConfigured } from '../../lib/whatsapp';
import { env } from '../../config/env';
import { feeReminderEmail } from '../../lib/email-templates';
import { invoiceNumber } from '../billing/invoice-pdf.service';
import { periodLabel } from '../notifications/notifications.service';
import { applyLateFeesEverywhere } from '../billing/billing-rules.service';
import { Role } from '@prisma/client';
import { runWithTenantContext } from '../../lib/tenantContext';
import { onlineCollectionFor } from '../payments/payment-account.service';
import { createOrReuseRequest } from '../payments/payment-requests.service';
import { flagLateReturns } from '../gate/gate.service';
import { postSalariesEverywhere } from '../subadmins/salary.service';
import { releaseExpiredReservations } from '../enquiries/enquiries.service';
import { runPlanReminders } from '../platform/plan-reminders.service';
import { runDueReportSchedules } from '../reports/reports.service';
import { runEscalations } from '../requests/grievance.service';
import { runCleaningPass } from '../cleaning/cleaning.service';
import { runCurfewPass } from '../outings/outings.service';
import { runBusOverduePass } from '../transport/transport.service';
import { runEnergyPass } from '../energy/energy-kpi.service';
import { runEventReminders } from '../events/events.service';
import { runAppointmentReminders } from '../medical/medical.service';
import { runCompliancePass } from '../compliance/compliance.service';

/**
 * The automatic dues reminders.
 *
 * A tenant sets up to three offsets — say 15, 10 and 1 day before the due
 * date — and every pending invoice gets one nudge per offset, by email and
 * WhatsApp, when its due date is exactly that many days away.
 *
 * ReminderLog is what makes this safe to run as often as we like: one row per
 * (invoice, offset, channel), written before success is known, so a student is
 * never nagged twice for the same thing even across restarts. The hourly tick
 * plus the unique constraint IS the scheduler — no cron infrastructure.
 *
 * This is a background job with no request context, so it deliberately uses
 * the UNSCOPED client and carries the tenantId explicitly through every query.
 */

const DAY_MS = 86_400_000;

function todayUtc(): Date {
  const now = new Date();
  return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
}

export interface ReminderRunResult {
  invoicesDue: number;
  emailed: number;
  whatsapped: number;
  skippedAlreadySent: number;
  mode: { email: string; whatsapp: string };
}

/** Run one tenant's reminder pass. Also the "send now" behind the test button. */
export async function runRemindersForTenant(tenantId: string): Promise<ReminderRunResult> {
  const result: ReminderRunResult = {
    invoicesDue: 0,
    emailed: 0,
    whatsapped: 0,
    skippedAlreadySent: 0,
    mode: { email: isEmailConfigured() ? 'live' : 'dry-run', whatsapp: isWhatsAppConfigured() ? 'live' : 'dry-run' },
  };

  const settings = await prismaUnscoped.tenantSettings.findUnique({ where: { tenantId } });
  const dorm = await isDormitoryTenant(tenantId);
  if (!settings?.remindersEnabled || settings.reminderDaysBefore.length === 0) return result;

  const today = todayUtc();
  const offsets = [...new Set(settings.reminderDaysBefore)].filter((d) => d >= 0 && d <= 60);
  // With online collection on, every reminder carries a link to pay. A
  // gateway hiccup must not stop the reminder itself, so the link is best effort.
  const online = await onlineCollectionFor(tenantId);
  const payLink = async (invoiceId: string, userId: string): Promise<{ url: string; amount: number } | null> => {
    if (!online.enabled) return null;
    try {
      const r = await runWithTenantContext({ tenantId, userId, role: Role.HOSTEL_ADMIN }, () => createOrReuseRequest(invoiceId, { origin: 'REMINDER' }));
      return r.linkUrl ? { url: r.linkUrl, amount: r.grossAmount } : null;
    } catch {
      return null;
    }
  };

  for (const daysBefore of offsets) {
    // Invoices whose due date is exactly `daysBefore` days from today.
    const target = new Date(today.getTime() + daysBefore * DAY_MS);
    const nextDay = new Date(target.getTime() + DAY_MS);
    const invoices = await prismaUnscoped.invoice.findMany({
      where: { tenantId, status: { not: InvoiceStatus.PAID }, dueDate: { gte: target, lt: nextDay } },
      include: {
        payments: { where: { status: 'CLEARED' }, select: { amount: true } },
        student: { include: { user: { select: { id: true, name: true, email: true, phone: true } } } },
      },
    });

    for (const inv of invoices) {
      result.invoicesDue++;
      const balance = inv.amount - inv.payments.reduce((n, p) => n + p.amount, 0);
      if (balance <= 0) continue;
      const kind = inv.type === 'RENT' ? 'rent' : inv.type === 'MESS' ? 'mess fee' : 'charges';
      const when = daysBefore === 0 ? 'today' : daysBefore === 1 ? 'tomorrow' : `in ${daysBefore} days`;
      const link = inv.student.user.email || inv.student.user.phone ? await payLink(inv.id, inv.student.user.id) : null;
      const text = `Hi ${inv.student.user.name}, your hostel ${kind} of ₹${balance} for ${inv.periodMonth} is due ${when}.${link ? ` Pay online: ${link.url}` : ''} Please pay to avoid a late fee. — ${settings.billingFirmName ?? 'HostelCare'}`;

      for (const channel of ['EMAIL', 'WHATSAPP'] as const) {
        const to = channel === 'EMAIL' ? inv.student.user.email : inv.student.user.phone;
        if (!to) continue;
        // Claim the (invoice, offset, channel) slot FIRST. If two ticks race,
        // the unique constraint lets exactly one of them through.
        try {
          await prismaUnscoped.reminderLog.create({ data: { tenantId, invoiceId: inv.id, daysBefore, channel } });
        } catch {
          result.skippedAlreadySent++;
          continue;
        }
        if (channel === 'EMAIL') {
          const mail = feeReminderEmail({
            firm: settings.billingFirmName ?? 'HostelCare',
            brand: brandFromSettings(settings),
            studentName: inv.student.user.name,
            when,
            overdue: false,
            invoice: {
              number: invoiceNumber(inv.id, inv.periodMonth),
              kind: invoiceKindWord(inv.type, dorm),
              periodLabel: periodLabel(inv.periodMonth, inv.cycleMonths),
              amount: inv.amount,
              paid: inv.amount - balance,
              balance,
              dueDate: inv.dueDate ? inv.dueDate.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', timeZone: 'UTC' }) : null,
            },
            payUrl: link?.url ?? null,
            payAmount: link?.amount ?? null,
          });
          await sendEmail(to, mail.subject, mail.text, mail.html);
          result.emailed++;
        } else {
          // Outside a 24-hour conversation Meta delivers templates only; the
          // reminder template takes name, amount, invoice/period, when, link.
          if (env.WHATSAPP_TEMPLATE_REMINDER) {
            await sendWhatsAppTemplate(to, env.WHATSAPP_TEMPLATE_REMINDER, [inv.student.user.name, `₹${balance}`, `${kind} · ${inv.periodMonth}`, when, link?.url ?? 'the HostelCare app'], text, { tenantId, userId: inv.student.user.id, purpose: 'FEE_REMINDER' });
          } else {
            await sendWhatsApp(to, text, { tenantId, userId: inv.student.user.id, purpose: 'FEE_REMINDER' });
          }
          result.whatsapped++;
        }
      }
    }
  }
  return result;
}

/** Every tenant with reminders on — the hourly tick. */
export async function runAllReminders(): Promise<void> {
  const tenants = await prismaUnscoped.tenantSettings.findMany({
    where: { remindersEnabled: true },
    select: { tenantId: true },
  });
  for (const t of tenants) {
    try {
      await runRemindersForTenant(t.tenantId);
    } catch (err) {
      // One tenant's failure must not stop the rest of the pass.
      // eslint-disable-next-line no-console
      console.error(`Reminder pass failed for tenant ${t.tenantId}:`, err);
    }
  }
}

let timer: NodeJS.Timeout | null = null;

/**
 * Hourly, not daily: a due date is matched by whole UTC day, and the log makes
 * repeats free, so running often just means the nudge lands within an hour of
 * the day starting rather than whenever the server happened to boot.
 */
export function startReminderScheduler(): void {
  if (timer) return;
  // Late fees first, so a reminder sent in the same tick quotes the new balance.
  // The late-fee pass is a no-op for every hostel that has not switched it on.
  const tick = async () => {
    await applyLateFeesEverywhere();
    await runAllReminders();
    // Gate passes past their return time with no In: flag and tell people.
    await flagLateReturns().catch((err) => console.error('[gate] late-return pass failed:', err)); // eslint-disable-line no-console
    // Sprint 6: salaries whose pay day has come, and bed holds that have lapsed.
    await postSalariesEverywhere().catch((err) => console.error('[salary] pass failed:', err)); // eslint-disable-line no-console
    await releaseExpiredReservations().catch((err) => console.error('[enquiries] expiry pass failed:', err)); // eslint-disable-line no-console
    // Sprint 0 (TEPL): scheduled Excel reports whose hour has come.
    await runDueReportSchedules().catch((err) => console.error('[reports] schedule pass failed:', err)); // eslint-disable-line no-console
    // Sprint 2 (TEPL): complaints and repairs past their target are escalated.
    await runEscalations().catch((err) => console.error('[grievance] escalation pass failed:', err)); // eslint-disable-line no-console
    // Sprint 3 (TEPL): today's cleaning tasks, and yesterday's not done marked missed.
    await runCleaningPass().catch((err) => console.error('[cleaning] pass failed:', err)); // eslint-disable-line no-console
    // Sprint 4 (TEPL): out after curfew, buses not back, high energy use and the BMS pull.
    await runCurfewPass().catch((err) => console.error('[curfew] pass failed:', err)); // eslint-disable-line no-console
    await runBusOverduePass().catch((err) => console.error('[transport] pass failed:', err)); // eslint-disable-line no-console
    await runEnergyPass().catch((err) => console.error('[energy] pass failed:', err)); // eslint-disable-line no-console
    // Sprint 5 (TEPL): events starting within two hours remind those registered.
    await runEventReminders().catch((err) => console.error('[events] reminders failed:', err)); // eslint-disable-line no-console
    // Sprint 6 (TEPL): OHC appointments in the next day remind the employee.
    await runAppointmentReminders().catch((err) => console.error('[medical] reminders failed:', err)); // eslint-disable-line no-console
    await runCompliancePass().catch((err) => console.error('[compliance] reminders failed:', err)); // eslint-disable-line no-console
    // Platform: plan expiry reminders to hostels, and Monday's summary to the
    // super admin. Under the test clock the suites drive it themselves.
    if (!env.CRM_TEST_CLOCK) await runPlanReminders().catch((err) => console.error('[plans] expiry reminder pass failed:', err)); // eslint-disable-line no-console
  };
  timer = setInterval(() => void tick(), 60 * 60 * 1000);
  timer.unref(); // never keep the process alive just to nag people
  setTimeout(() => void tick(), 15_000).unref();
}
