import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Prisma, Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requireAnyPermission, requirePermission } from '../../middleware/requirePermission';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { getMe } from '../auth/auth.service';
import { getPagination, getSearch, paginated } from '../../lib/pagination';
import { BadRequestError } from '../../lib/errors';
import * as notify from '../notifications/notifications.service';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { requireFeature } from '../../middleware/requireFeature';
import { audienceCountsForNotices, audienceMembers, isTargeted, noticeWhereFor, type Audience } from '../communication/audience';

/** Sprint 4 (TEPL): categories beyond General and Mess, for employee hostels. */
const MORE_CATEGORIES = ['MAINTENANCE', 'SAFETY', 'EVENT', 'HR', 'TRANSPORT'] as const;

const createSchema = z.object({
  title: z.string().min(2).max(140),
  body: z.string().min(1).max(4000),
  category: z.enum(['GENERAL', 'MESS', ...MORE_CATEGORIES]).default('GENERAL'),
  /** Important notices are emailed to everyone in the hostel. */
  important: z.boolean().optional().default(false),
  // Sprint 4 (TEPL), with noticeTargeting on: who it is for, and a read receipt.
  propertyId: z.string().uuid().nullable().optional(),
  floors: z.array(z.number().int().min(-5).max(200)).max(50).optional(),
  shiftIds: z.array(z.string().uuid()).max(20).optional(),
  departmentIds: z.array(z.string().uuid()).max(50).optional(),
  requireAck: z.boolean().optional(),
});

/** Null means every category, which is the default view. */
const categoryQuery = z.object({
  category: z.enum(['GENERAL', 'MESS', ...MORE_CATEGORIES]).optional(),
});

export const noticeRouter = Router();

// Everyone signed in (incl. students) can read their tenant's notices.
noticeRouter.get(
  '/',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    const pagination = getPagination(req.query);
    const q = getSearch(req.query);
    const parsedCategory = categoryQuery.safeParse(req.query);
    if (!parsedCategory.success) {
      throw new BadRequestError(parsedCategory.error.issues[0].message);
    }

    // Both narrow together: a search inside Mess must not surface a General
    // notice, and vice versa.
    // Sprint 4 (TEPL): a resident reads the notices meant for them, and sees which they acknowledged.
    const tenantId = getTenantIdOrThrow();
    const targeting = await tenantHasFeature(tenantId, 'noticeTargeting');
    const forResident = targeting && req.user!.role === Role.STUDENT ? await noticeWhereFor(tenantId, req.user!.sub) : null;
    const where: Prisma.NoticeWhereInput = {
      ...(forResident ?? {}),
      ...(parsedCategory.data.category ? { category: parsedCategory.data.category } : {}),
      ...(q
        ? {
            OR: [
              { title: { contains: q, mode: 'insensitive' as const } },
              { body: { contains: q, mode: 'insensitive' as const } },
              // The web searches the author too, so the server must as well
              // — once the list is paged, a client cannot make up the gap.
              { postedByName: { contains: q, mode: 'insensitive' as const } },
            ],
          }
        : {}),
    };
    const orderBy = { createdAt: 'desc' as const };

    const withAcks = async <T extends { id: string; requireAck: boolean } & Audience>(rows: T[]) => {
      if (!targeting || !rows.some((n) => n.requireAck)) return rows;
      const ids = rows.filter((n) => n.requireAck).map((n) => n.id);
      if (req.user!.role === Role.STUDENT) {
        const mine = await db.noticeAck.findMany({ where: { userId: req.user!.sub, noticeId: { in: ids } }, select: { noticeId: true, ackedAt: true } });
        const at = new Map(mine.map((a) => [a.noticeId, a.ackedAt]));
        return rows.map((n) => (n.requireAck ? { ...n, ackedAt: at.get(n.id) ?? null } : n));
      }
      const counts = await db.noticeAck.groupBy({ by: ['noticeId'], where: { noticeId: { in: ids } }, _count: { _all: true } });
      const count = new Map(counts.map((c) => [c.noticeId, c._count._all]));
      // Out of how many: the audience as it stands now, one grouped query for the lot.
      const totals = await audienceCountsForNotices(tenantId, rows.filter((n) => n.requireAck));
      return rows.map((n) => (n.requireAck ? { ...n, ackCount: count.get(n.id) ?? 0, ackTotal: totals.get(n.id) ?? 0 } : n));
    };

    if (!pagination) {
      res.json({ notices: await withAcks(await db.notice.findMany({ where, orderBy })) });
      return;
    }

    const [items, total] = await Promise.all([
      db.notice.findMany({ where, orderBy, skip: pagination.skip, take: pagination.limit }),
      db.notice.count({ where }),
    ]);
    res.json(paginated(await withAcks(items), total, pagination));
  }),
);

// Anyone with POST_NOTICES can post.
noticeRouter.post(
  '/',
  authenticate,
  requirePermission('POST_NOTICES'),
  asyncHandler(async (req: Request, res: Response) => {
    const input = createSchema.parse(req.body);
    // Mess Admin may only post mess-related notices.
    if (req.user!.role === Role.MESS_ADMIN && input.category !== 'MESS') {
      res.status(403).json({ error: 'Mess Admin can only post MESS notices' });
      return;
    }
    const me = await getMe(req.user!.sub);
    const tenantId = getTenantIdOrThrow();
    const audience = { propertyId: input.propertyId ?? null, floors: input.floors ?? [], shiftIds: input.shiftIds ?? [], departmentIds: input.departmentIds ?? [] };
    const extras = isTargeted(audience) || input.requireAck || (MORE_CATEGORIES as readonly string[]).includes(input.category);
    if (extras && !(await tenantHasFeature(tenantId, 'noticeTargeting'))) throw new BadRequestError('Targeted notices are not switched on for this account');
    if (audience.propertyId && !(await db.property.findFirst({ where: { id: audience.propertyId }, select: { id: true } }))) throw new BadRequestError('Unknown block');
    const notice = await db.notice.create({
      data: {
        tenantId,
        title: input.title,
        body: input.body,
        category: input.category,
        important: input.important,
        postedById: me.id,
        postedByName: me.name,
        ...audience,
        requireAck: !!input.requireAck,
      },
    });
    res.status(201).json({ notice });
    if (notice.important) notify.inBackground('notice', () => notify.notifyNoticePosted(tenantId, notice.id));
    // One that asks to be acknowledged reaches its readers' inbox even when it is not marked important.
    else if (notice.requireAck)
      notify.inBackground('notice: ack', async () => {
        const members = await audienceMembers(tenantId, audience);
        await notify.pushTo(tenantId, 'NOTICE', notice.id, members.map((m) => m.userId), { title: notice.title, body: 'Please read and acknowledge this notice.', data: { noticeId: notice.id } });
      });
  }),
);

noticeRouter.delete(
  '/:id',
  authenticate,
  requirePermission('POST_NOTICES'),
  asyncHandler(async (req: Request, res: Response) => {
    const existing = await db.notice.findFirst({ where: { id: req.params.id } });
    if (!existing) {
      res.status(404).json({ error: 'Notice not found' });
      return;
    }
    await db.noticeAck.deleteMany({ where: { noticeId: req.params.id } });
    await db.notice.delete({ where: { id: req.params.id } });
    res.status(204).send();
  }),
);

// ── Sprint 4 (TEPL): read acknowledgement ───────────────────────────────────

/**
 * The audience picker's choices, for whoever posts notices: the blocks, the
 * floors with rooms in each, the shifts and the departments. Names only — a
 * poster without access to residents or the roster still targets by them.
 */
noticeRouter.get(
  '/audience-options',
  authenticate,
  requireFeature('noticeTargeting'),
  // The events desk targets events the same way (Sprint 5).
  requireAnyPermission('POST_NOTICES', 'MANAGE_EVENTS'),
  asyncHandler(async (_req: Request, res: Response) => {
    const [blocks, floors, shifts, departments] = await Promise.all([
      db.property.findMany({ where: { isArchived: false }, select: { id: true, name: true }, orderBy: { name: 'asc' } }),
      db.room.groupBy({ by: ['propertyId', 'floor'], where: { archivedAt: null, floor: { not: null } } }),
      db.shift.findMany({ select: { id: true, code: true, name: true, isActive: true, isOff: true, startTime: true, endTime: true, sortOrder: true }, orderBy: { sortOrder: 'asc' } }),
      db.department.findMany({ select: { id: true, name: true, code: true, isArchived: true }, orderBy: { name: 'asc' } }),
    ]);
    res.json({ blocks, floors: floors.map((f) => ({ propertyId: f.propertyId, floor: f.floor })), shifts, departments });
  }),
);

/** A resident acknowledges a notice meant for them. */
noticeRouter.post(
  '/:id/ack',
  authenticate,
  requireFeature('noticeTargeting'),
  asyncHandler(async (req: Request, res: Response) => {
    if (req.user!.role !== Role.STUDENT) throw new BadRequestError('Only residents acknowledge notices');
    const tenantId = getTenantIdOrThrow();
    const notice = await db.notice.findFirst({ where: { AND: [{ id: req.params.id }, await noticeWhereFor(tenantId, req.user!.sub)] }, select: { id: true, requireAck: true } });
    if (!notice) {
      res.status(404).json({ error: 'Notice not found' });
      return;
    }
    if (!notice.requireAck) throw new BadRequestError('This notice does not ask for an acknowledgement');
    const ack = await db.noticeAck.upsert({ where: { noticeId_userId: { noticeId: notice.id, userId: req.user!.sub } }, create: { tenantId, noticeId: notice.id, userId: req.user!.sub }, update: {} });
    res.json({ ackedAt: ack.ackedAt });
  }),
);

/** Who has acknowledged, and who has not yet, among those it was for. */
noticeRouter.get(
  '/:id/acks',
  authenticate,
  requireFeature('noticeTargeting'),
  requirePermission('POST_NOTICES'),
  asyncHandler(async (req: Request, res: Response) => {
    const tenantId = getTenantIdOrThrow();
    const notice = await db.notice.findFirst({ where: { id: req.params.id } });
    if (!notice) {
      res.status(404).json({ error: 'Notice not found' });
      return;
    }
    const [members, acks] = await Promise.all([audienceMembers(tenantId, notice), db.noticeAck.findMany({ where: { noticeId: notice.id } })]);
    const at = new Map(acks.map((a) => [a.userId, a.ackedAt]));
    res.json({
      requireAck: notice.requireAck,
      total: members.length,
      acked: members.filter((m) => at.has(m.userId)).map((m) => ({ userId: m.userId, name: m.name, room: m.room, ackedAt: at.get(m.userId) })),
      pending: members.filter((m) => !at.has(m.userId)).map((m) => ({ userId: m.userId, name: m.name, room: m.room, phone: m.phone })),
    });
  }),
);

