import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { InvoiceStatus, InvoiceType } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requirePermission } from '../../middleware/requirePermission';
import { db } from '../../lib/prisma';
import { isValidPeriod } from '../../lib/period';
import { BadRequestError } from '../../lib/errors';
import { isWhatsAppConfigured, sendWhatsApp } from '../../lib/whatsapp';

export const reminderRouter = Router();

/** Whether real WhatsApp sending is live (else dry-run/log mode). */
reminderRouter.get(
  '/status',
  authenticate,
  requirePermission('MANAGE_RENT'),
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ configured: isWhatsAppConfigured(), mode: isWhatsAppConfigured() ? 'live' : 'dry-run' });
  }),
);

/** Send rent reminders to students with a PENDING rent invoice for the period. */
reminderRouter.post(
  '/rent',
  authenticate,
  requirePermission('MANAGE_RENT'),
  asyncHandler(async (req: Request, res: Response) => {
    const period = z.object({ period: z.string().refine(isValidPeriod) }).parse(req.body).period;
    const invoices = await db.invoice.findMany({
      where: { type: InvoiceType.RENT, periodMonth: period, status: { not: InvoiceStatus.PAID } },
      include: { student: { include: { user: { select: { id: true, name: true, phone: true } } } }, payments: { where: { status: 'CLEARED' }, select: { amount: true } } },
    });

    let sent = 0;
    let skippedNoPhone = 0;
    let live = 0;
    for (const inv of invoices) {
      const phone = inv.student.user.phone;
      if (!phone) {
        skippedNoPhone++;
        continue;
      }
      const paid = inv.payments.reduce((n, p) => n + p.amount, 0);
      const balance = inv.amount - paid;
      const text = `Hi ${inv.student.user.name}, your hostel rent of ₹${balance} for ${period} is pending. Please pay at your earliest. — HostelCare`;
      const result = await sendWhatsApp(phone, text, { userId: inv.student.user.id, purpose: 'RENT_REMINDER' });
      sent++;
      if (result.sent) live++;
    }
    res.json({ recipients: invoices.length, sent, deliveredLive: live, skippedNoPhone, mode: isWhatsAppConfigured() ? 'live' : 'dry-run' });
  }),
);

/** Broadcast a free-text message to every student with a phone on file. */
reminderRouter.post(
  '/broadcast',
  authenticate,
  requirePermission('MANAGE_RENT'),
  asyncHandler(async (req: Request, res: Response) => {
    const message = z.object({ message: z.string().min(1).max(1000) }).parse(req.body).message;
    const students = await db.studentProfile.findMany({ include: { user: { select: { id: true, name: true, phone: true } } } });
    const withPhone = students.filter((s) => s.user.phone);
    if (withPhone.length === 0) throw new BadRequestError('No students have a phone number on file');

    let live = 0;
    for (const s of withPhone) {
      const result = await sendWhatsApp(s.user.phone!, message, { userId: s.user.id, purpose: 'BROADCAST' });
      if (result.sent) live++;
    }
    res.json({ recipients: withPhone.length, deliveredLive: live, skippedNoPhone: students.length - withPhone.length, mode: isWhatsAppConfigured() ? 'live' : 'dry-run' });
  }),
);
