import { Request, Response, NextFunction } from 'express'; import { creaInvito, getInvitoPubblico, accettaInvito } from '../services/inviti.service'; import { HttpError } from '../errors'; interface PostInvitoBody { email?: unknown; ruolo?: unknown; } function parseCreaInvitoBody(body: PostInvitoBody): { email: string; ruolo: string } { if (typeof body.email !== 'string' || body.email.trim().length === 0) { throw new HttpError(400, "Il campo 'email' è obbligatorio ed è una stringa non vuota"); } if (typeof body.ruolo !== 'string' || body.ruolo.trim().length === 0) { throw new HttpError(400, "Il campo 'ruolo' è obbligatorio ed è una stringa non vuota"); } return { email: body.email, ruolo: body.ruolo }; } export async function postInvito(req: Request, res: Response, next: NextFunction): Promise { try { const { orgId } = req.params; const { email, ruolo } = parseCreaInvitoBody(req.body ?? {}); const result = await creaInvito({ orgId, email, ruolo }); res.status(201).json(result); } catch (err) { next(err); } } export async function getInvito(req: Request, res: Response, next: NextFunction): Promise { try { const { token } = req.params; const invito = await getInvitoPubblico(token); if (!invito) { throw new HttpError(404, 'Invito non trovato'); } res.json(invito); } catch (err) { next(err); } } export async function postAccettaInvito(req: Request, res: Response, next: NextFunction): Promise { try { const { token } = req.params; const result = await accettaInvito(token, { userId: req.auth!.userId, email: req.auth!.email, }); res.status(200).json(result); } catch (err) { next(err); } }