import type { FastifyInstance } from 'fastify';
import { authenticate } from '../middleware/auth.js';
import { portalService } from '../services/portalService.js';

export async function portalRoutes(fastify: FastifyInstance) {
  fastify.post('/messages', { preHandler: authenticate }, async (req, reply) => {
    if (req.user!.role !== 'company_user') {
      return reply.status(403).send({ error: 'Company portal users only' });
    }
    const cid = req.user!.company_id ?? null;
    if (!cid) return reply.status(403).send({ error: 'Company not assigned' });

    const { content, ticket_id } = req.body as { content?: string; ticket_id?: string };
    try {
      const result = await portalService.postInboundFromCompanyUser({
        io: fastify.io,
        log: fastify.log,
        userId: req.user!.sub,
        companyId: cid,
        content: content ?? '',
        ticketId: ticket_id,
      });
      return reply.status(201).send(result);
    } catch (e: unknown) {
      const err = e as { statusCode?: number; message?: string };
      return reply.status(err.statusCode ?? 500).send({ error: err.message ?? 'Error' });
    }
  });
}
