import { Router, Request, Response } from 'express';
import { randomBytes } from 'node:crypto';
import { z } from 'zod';
import { DevicePurpose, PunchType, TenantKind } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requirePermission } from '../../middleware/requirePermission';
import { propertyContext } from '../../middleware/propertyContext';
import { deviceAuth } from '../../middleware/deviceAuth';
import { db } from '../../lib/prisma';
import { hashPassword } from '../../lib/password';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { isValidPeriod } from '../../lib/period';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import * as svc from './biometric.service';
import { getPagination, getSearch, paginated } from '../../lib/pagination';
import { tenantKindOf } from '../../middleware/requireFeature';

export const biometricRouter = Router();

// ── Device-authenticated ingestion (no JWT — terminals push here) ───────────
const punchSchema = z.object({
  punches: z
    .array(
      z.object({
        biometricId: z.string().min(1).max(64),
        punchedAt: z.string().min(4),
        type: z.nativeEnum(PunchType).optional(),
      }),
    )
    .min(1)
    .max(500),
});

/** The punch types each terminal purpose may send; system feeds (BMS, tags, HR, laundry) send none. */
const PUNCH_TYPES: Partial<Record<DevicePurpose, PunchType[]>> = {
  GATE: [PunchType.GATE_IN, PunchType.GATE_OUT],
  MESS: [PunchType.MESS],
  ROLLCALL: [PunchType.ROLLCALL],
};

biometricRouter.post(
  '/punches',
  deviceAuth,
  asyncHandler(async (req: Request, res: Response) => {
    const { punches } = punchSchema.parse(req.body);
    // Each terminal sends only its own kind of punch (Sprint 7 hardening): a
    // canteen key cannot post gate swipes, and system feeds send none at all.
    const allowed = PUNCH_TYPES[req.device!.purpose];
    if (!allowed) throw new BadRequestError('This key is for a system feed, not punches');
    // Enterprise tenants only: terminals in the field elsewhere keep sending what they send.
    const strict = (await tenantKindOf(req.device!.tenantId)) === TenantKind.ENTERPRISE;
    const wrong = strict ? punches.find((p) => p.type && !allowed.includes(p.type)) : undefined;
    if (wrong) throw new BadRequestError(`A ${req.device!.purpose.toLowerCase()} terminal cannot send ${wrong.type} punches`);
    const result = await svc.ingestPunches(req.device!, punches);
    res.status(201).json(result);
  }),
);

// ── Admin: device management + read models ─────────────────────────────────
const manage = [authenticate, propertyContext, requirePermission('MANAGE_DEVICES')] as const;

/**
 * Keys for machines rather than terminals: the BMS, ZoTag, TEPL's HR systems
 * and the laundry provider. Their data approves leave, sets the roster and
 * moves records, so only the owner's level (MANAGE_STAFF) may issue or
 * rotate one — not every warden who manages terminals.
 */
const MACHINE_PURPOSES: DevicePurpose[] = [DevicePurpose.BMS, DevicePurpose.ASSET_TAGS, DevicePurpose.HR_FEED, DevicePurpose.LAUNDRY];
async function assertMayKey(req: Request, purpose: DevicePurpose) {
  if (MACHINE_PURPOSES.includes(purpose) && (await tenantKindOf(req.user!.tenantId!)) !== TenantKind.ENTERPRISE) throw new BadRequestError('Invalid device purpose');
  if (MACHINE_PURPOSES.includes(purpose) && !req.user!.perms.includes('MANAGE_STAFF')) throw new ForbiddenError('Only the owner (or a sub-admin who manages staff) can issue a key for a system feed');
}

const createDeviceSchema = z.object({
  name: z.string().min(2).max(80),
  serialNumber: z.string().min(3).max(64),
  purpose: z.nativeEnum(DevicePurpose).default(DevicePurpose.GATE),
});

biometricRouter.get(
  '/devices/stats',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ stats: await svc.deviceStats(req.propertyId) });
  }),
);

biometricRouter.get(
  '/devices',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    const pagination = getPagination(req.query);
    const q = getSearch(req.query);
    const where = {
      // Property-specific devices show under their property; devices with no
      // property (e.g. a shared main gate) stay visible everywhere.
      ...(req.propertyId
        ? { OR: [{ propertyId: req.propertyId }, { propertyId: null }] }
        : {}),
      ...(q
        ? {
            AND: [
              {
                OR: [
                  { name: { contains: q, mode: 'insensitive' as const } },
                  { serialNumber: { contains: q, mode: 'insensitive' as const } },
                ],
              },
            ],
          }
        : {}),
    };
    const include = {
      _count: { select: { punches: true } },
      property: { select: { name: true } },
    };
    const orderBy = { createdAt: 'asc' as const };
    // The key hash never leaves the server.
    const shape = <T extends { apiKeyHash: string; _count: { punches: number } }>({
      apiKeyHash: _hash,
      _count,
      ...d
    }: T) => ({ ...d, punchCount: _count.punches });

    if (!pagination) {
      const devices = await db.biometricDevice.findMany({ where, include, orderBy });
      res.json({ devices: devices.map(shape) });
      return;
    }

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

biometricRouter.post(
  '/devices',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    const input = createDeviceSchema.parse(req.body);
    await assertMayKey(req, input.purpose);
    const clash = await db.biometricDevice.findFirst({ where: { serialNumber: input.serialNumber } });
    if (clash) throw new ConflictError('A device with that serial number already exists');

    // Show the key exactly once — only its hash is stored.
    const apiKey = `hc_dev_${randomBytes(24).toString('base64url')}`;
    const device = await db.biometricDevice.create({
      data: {
        tenantId: getTenantIdOrThrow(),
        propertyId: req.propertyId ?? null,
        name: input.name,
        serialNumber: input.serialNumber,
        purpose: input.purpose,
        apiKeyHash: await hashPassword(apiKey),
      },
    });
    const { apiKeyHash: _hash, ...safe } = device;
    res.status(201).json({ device: safe, apiKey });
  }),
);

biometricRouter.post(
  '/devices/:id/rotate-key',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    const device = await db.biometricDevice.findFirst({ where: { id: req.params.id } });
    if (!device) throw new NotFoundError('Device not found');
    await assertMayKey(req, device.purpose);
    const apiKey = `hc_dev_${randomBytes(24).toString('base64url')}`;
    await db.biometricDevice.update({ where: { id: device.id }, data: { apiKeyHash: await hashPassword(apiKey) } });
    res.json({ apiKey });
  }),
);

biometricRouter.delete(
  '/devices/:id',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    const device = await db.biometricDevice.findFirst({ where: { id: req.params.id } });
    if (!device) throw new NotFoundError('Device not found');
    await db.biometricPunch.deleteMany({ where: { deviceId: device.id } });
    await db.biometricDevice.delete({ where: { id: device.id } });
    res.status(204).send();
  }),
);

biometricRouter.get(
  '/punches',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    const type = req.query.type as PunchType | undefined;
    const limit = req.query.limit ? Number(req.query.limit) : undefined;
    const pagination = getPagination(req.query);
    const result = await svc.listPunches({ type, limit, propertyId: req.propertyId }, pagination);
    res.json(pagination ? result : { punches: result });
  }),
);

biometricRouter.get(
  '/presence',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await svc.getPresence(req.propertyId));
  }),
);

biometricRouter.get(
  '/rollcall',
  ...manage,
  asyncHandler(async (req: Request, res: Response) => {
    const period = String(req.query.period ?? '');
    if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
    res.json(await svc.getRollcall(period, req.propertyId));
  }),
);
