import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { env } from '../../config/env';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requirePermission } from '../../middleware/requirePermission';
import { db } from '../../lib/prisma';
import { isWhatsAppConfigured } from '../../lib/whatsapp';

/**
 * A hostel's WhatsApp messages (12 Oct 2026): what went out with its delivery
 * status, and the replies that came back. Same permission as sending the
 * reminders. Scoped client: a hostel sees only its own rows.
 */

export const whatsappRouter = Router();
whatsappRouter.use(authenticate, requirePermission('MANAGE_RENT'));

const unseen = { direction: 'IN', seenAt: null } as const;

whatsappRouter.get(
  '/summary',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({
      unread: await db.whatsAppMessage.count({ where: unseen }),
      sending: isWhatsAppConfigured(),
      receiving: !!env.WHATSAPP_APP_SECRET && !!env.WHATSAPP_VERIFY_TOKEN,
    });
  }),
);

whatsappRouter.get(
  '/messages',
  asyncHandler(async (req: Request, res: Response) => {
    const q = z
      .object({
        show: z.enum(['all', 'replies', 'unread', 'sent', 'failed']).default('all'),
        before: z.string().datetime().optional(),
        limit: z.coerce.number().int().min(1).max(100).default(50),
      })
      .parse(req.query);
    const where = {
      ...(q.show === 'replies' ? { direction: 'IN' } : q.show === 'unread' ? unseen : q.show === 'sent' ? { direction: 'OUT' } : q.show === 'failed' ? { direction: 'OUT', status: 'failed' } : {}),
      ...(q.before ? { createdAt: { lt: new Date(q.before) } } : {}),
    };
    const rows = await db.whatsAppMessage.findMany({
      where,
      orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
      take: q.limit + 1,
      select: { id: true, direction: true, phone: true, userId: true, profileName: true, kind: true, body: true, purpose: true, status: true, error: true, createdAt: true, deliveredAt: true, readAt: true, failedAt: true, seenAt: true },
    });
    const page = rows.slice(0, q.limit);
    const ids = [...new Set(page.map((r) => r.userId).filter((x): x is string => !!x))];
    const users = ids.length ? await db.user.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } }) : [];
    const name = new Map(users.map((u) => [u.id, u.name]));
    res.json({
      items: page.map((r) => ({ ...r, userName: r.userId ? name.get(r.userId) ?? null : null })),
      hasMore: rows.length > q.limit,
    });
  }),
);

/** Mark replies seen: the ids given, or every unseen one. */
whatsappRouter.post(
  '/messages/seen',
  asyncHandler(async (req: Request, res: Response) => {
    const { ids } = z.object({ ids: z.array(z.string().uuid()).max(200).optional() }).parse(req.body ?? {});
    const r = await db.whatsAppMessage.updateMany({ where: { ...unseen, ...(ids ? { id: { in: ids } } : {}) }, data: { seenAt: new Date() } });
    res.json({ updated: r.count });
  }),
);
