import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requirePermission } from '../../middleware/requirePermission';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { PERMISSIONS, PERMISSION_FEATURE } from '../../lib/permissions';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { getPagination, getSearch, paginated } from '../../lib/pagination';
import { announceMedicalAccess, guardRoleEdit } from '../medical/medical-access';

const permsSchema = z.array(z.enum(PERMISSIONS)).min(1);
const createSchema = z.object({ name: z.string().min(2).max(60), permissions: permsSchema });
const updateSchema = z.object({ name: z.string().min(2).max(60).optional(), permissions: permsSchema.optional() });

async function assertOffered(tenantId: string, permissions: readonly (typeof PERMISSIONS)[number][] | undefined) {
  for (const p of permissions ?? []) {
    const feature = PERMISSION_FEATURE[p];
    if (feature && !(await tenantHasFeature(tenantId, feature))) throw new BadRequestError('Invalid permission');
  }
}

export const roleRouter = Router();
roleRouter.use(authenticate, requirePermission('MANAGE_STAFF'));

/** The permission catalog (what a custom role can grant). */
roleRouter.get(
  '/permissions',
  asyncHandler(async (req: Request, res: Response) => {
    // A permission that belongs to a module this hostel does not have is not offered.
    const offered = [];
    for (const p of PERMISSIONS) {
      const feature = PERMISSION_FEATURE[p];
      if (!feature || (await tenantHasFeature(req.user!.tenantId!, feature))) offered.push(p);
    }
    res.json({ permissions: offered });
  }),
);

roleRouter.get(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const pagination = getPagination(req.query);
    const q = getSearch(req.query);
    const where = q ? { name: { contains: q, mode: 'insensitive' as const } } : {};
    const include = { _count: { select: { users: true } } };
    const orderBy = { createdAt: 'desc' as const };
    const toRole = (r: { id: string; name: string; permissions: string[]; _count: { users: number } }) => ({
      id: r.id,
      name: r.name,
      permissions: r.permissions,
      userCount: r._count.users,
    });

    if (!pagination) {
      const roles = await db.customRole.findMany({ where, include, orderBy });
      res.json({ roles: roles.map(toRole) });
      return;
    }

    const [roles, total] = await Promise.all([
      db.customRole.findMany({ where, include, orderBy, skip: pagination.skip, take: pagination.limit }),
      db.customRole.count({ where }),
    ]);
    res.json(paginated(roles.map(toRole), total, pagination));
  }),
);

roleRouter.post(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = createSchema.parse(req.body);
    await assertOffered(getTenantIdOrThrow(), input.permissions);
    const role = await db.customRole.create({ data: { tenantId: getTenantIdOrThrow(), name: input.name, permissions: input.permissions } });
    res.status(201).json({ role: { id: role.id, name: role.name, permissions: role.permissions } });
  }),
);

roleRouter.patch(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const input = updateSchema.parse(req.body);
    await assertOffered(getTenantIdOrThrow(), input.permissions);
    const existing = await db.customRole.findFirst({ where: { id: req.params.id } });
    if (!existing) throw new NotFoundError('Role not found');
    const gaining = await guardRoleEdit(req.user!.sub, existing.id, input.permissions);
    const role = await db.customRole.update({ where: { id: req.params.id }, data: input });
    announceMedicalAccess(req.user!.sub, gaining);
    res.json({ role: { id: role.id, name: role.name, permissions: role.permissions } });
  }),
);

roleRouter.delete(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const role = await db.customRole.findFirst({ where: { id: req.params.id }, include: { _count: { select: { users: true } } } });
    if (!role) throw new NotFoundError('Role not found');
    if (role._count.users > 0) throw new ConflictError('Unassign this role from all staff before deleting it');
    await db.customRole.delete({ where: { id: req.params.id } });
    res.status(204).send();
  }),
);
