import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import { Role, TenantKind } from '@prisma/client';
import { prismaUnscoped } from '../lib/prisma';
import { verifyPassword } from '../lib/password';
import { TooManyRequestsError, UnauthorizedError } from '../lib/errors';
import { runWithTenantContext } from '../lib/tenantContext';
import { tenantKindOf } from './requireFeature';

/**
 * Authenticates a biometric terminal (ESSL or compatible) by serial number +
 * API key, sent as `X-Device-Serial` / `X-Device-Key`.
 *
 * Terminals are not users — they never hold a JWT — so this is a separate
 * credential path. Crucially it still binds the device's OWN tenant into the
 * AsyncLocalStorage context, so every downstream query is tenant-scoped
 * exactly like a user request: a device can only ever write to its own tenant.
 */
export function deviceAuth(req: Request, res: Response, next: NextFunction): void {
  deviceAuthImpl(req, res, next).catch(next);
}

// ── Sprint 7 hardening: limits per serial (serials are printed on terminals) ──

const WINDOW_MS = 60_000;
/** Calls a serial may make a minute — terminals batch, so this is generous. */
const MAX_CALLS = 120;
/** Wrong keys a serial may send before it is locked out for a while. */
const MAX_FAILURES = 10;
const LOCK_MS = 15 * 60_000;
/** A key already checked is trusted this long, so each push does not cost a bcrypt check. */
const VERIFIED_MS = 10 * 60_000;

const calls = new Map<string, { count: number; resetAt: number }>();
const failures = new Map<string, { count: number; until: number }>();
const verified = new Map<string, number>();
const sweep = setInterval(() => {
  const now = Date.now();
  for (const [k, v] of calls) if (v.resetAt <= now) calls.delete(k);
  for (const [k, v] of failures) if (v.until <= now) failures.delete(k);
  for (const [k, v] of verified) if (v <= now) verified.delete(k);
}, WINDOW_MS);
sweep.unref();

function countCall(serial: string) {
  const now = Date.now();
  const slot = calls.get(serial);
  if (!slot || slot.resetAt <= now) return void calls.set(serial, { count: 1, resetAt: now + WINDOW_MS });
  if (++slot.count > MAX_CALLS) throw new TooManyRequestsError('Too many calls from this device — slow down');
}

function failed(serial: string) {
  const now = Date.now();
  const f = failures.get(serial);
  failures.set(serial, { count: (f && f.until > now ? f.count : 0) + 1, until: now + LOCK_MS });
}

async function deviceAuthImpl(req: Request, _res: Response, next: NextFunction): Promise<void> {
  // Already checked before the body was read (app.ts): the tenant context bound then still wraps this.
  if (req.device) return next();
  const serial = req.header('x-device-serial');
  const key = req.header('x-device-key');
  if (!serial || !key) throw new UnauthorizedError('Missing device credentials');

  // Unscoped lookup: pre-auth, and the serial is globally unique.
  const device = await prismaUnscoped.biometricDevice.findUnique({ where: { serialNumber: serial } });
  if (!device || !device.isActive) throw new UnauthorizedError('Unknown or inactive device');

  // The call limit and the wrong-key lockout apply to enterprise tenants'
  // devices; terminals already in the field at other hostels carry on as they were.
  const limited = (await tenantKindOf(device.tenantId)) === TenantKind.ENTERPRISE;
  if (limited) {
    const lock = failures.get(serial);
    if (lock && lock.count >= MAX_FAILURES && lock.until > Date.now()) throw new TooManyRequestsError('Too many wrong keys for this device — try again later');
    countCall(serial);
  }

  // Keyed on the stored hash too, so a rotated key is checked afresh.
  const memo = createHash('sha256').update(`${device.apiKeyHash}\0${key}`).digest('hex');
  if ((verified.get(memo) ?? 0) <= Date.now()) {
    const ok = await verifyPassword(key, device.apiKeyHash);
    if (!ok) {
      if (limited) failed(serial);
      throw new UnauthorizedError('Invalid device key');
    }
    verified.set(memo, Date.now() + VERIFIED_MS);
  }

  req.device = { id: device.id, tenantId: device.tenantId, propertyId: device.propertyId, purpose: device.purpose };

  runWithTenantContext(
    // A device acts on behalf of the tenant, with no user-level permissions.
    { userId: `device:${device.id}`, role: Role.HOSTEL_ADMIN, tenantId: device.tenantId },
    () => next(),
  );
}
