import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import * as svc from './devices.service';

/**
 * /api/devices — the signed-in user's own phones, for push notifications.
 * Any signed-in role: students, guardians, guards and staff all get pushes.
 * The user is always the session's; the body only names the install.
 */
export const deviceRouter = Router();
deviceRouter.use(authenticate);

// FCM tokens are a few hundred characters; the bound only stops abuse.
const tokenSchema = z.string().trim().min(10).max(4096);

deviceRouter.post(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ token: tokenSchema, platform: z.enum(['ANDROID', 'IOS']) }).parse(req.body);
    await svc.registerDevice(req.user!.sub, input.token, input.platform);
    res.status(204).end();
  }),
);

deviceRouter.delete(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ token: tokenSchema }).parse(req.body ?? {});
    await svc.unregisterDevice(req.user!.sub, input.token);
    res.status(204).end();
  }),
);
