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

export async function portalRoutes(fastify: FastifyInstance) {
  /** Company name for the signed-in portal user (navbar, etc.) */
  fastify.get('/company', { 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 company = await companyService.getById(cid);
    if (!company) return reply.status(404).send({ error: 'Company not found' });
    return reply.send({ id: company.id, name: company.name });
  });

  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' });

    try {
      if (req.isMultipart()) {
        let ticket_id: string | undefined;
        let content = '';
        let force_new = false;
        const files: Array<{ buffer: Buffer; mimetype: string; filename: string }> = [];

        for await (const part of req.parts()) {
          if (part.type === 'file') {
            if (files.length >= MAX_MEDIA_FILES_PER_REQUEST) {
              return reply.status(400).send({
                error: `At most ${MAX_MEDIA_FILES_PER_REQUEST} files per request`,
              });
            }
            const filename =
              typeof (part as { filename?: string }).filename === 'string'
                ? (part as { filename: string }).filename
                : 'document';
            files.push({ buffer: await part.toBuffer(), mimetype: part.mimetype, filename });
          } else if (part.fieldname === 'ticket_id') {
            const v = String(part.value ?? '').trim();
            if (v) ticket_id = v;
          } else if (part.fieldname === 'content') {
            content = String(part.value ?? '');
          } else if (part.fieldname === 'force_new') {
            const v = String(part.value ?? '').trim().toLowerCase();
            force_new = v === 'true' || v === '1';
          }
        }

        const result = await portalService.postInboundFromCompanyUserWithFiles({
          io: fastify.io,
          log: fastify.log,
          userId: req.user!.sub,
          companyId: cid,
          content,
          ticketId: ticket_id,
          forceNew: force_new,
          files,
        });
        return reply.status(201).send(result);
      }

      const { content, ticket_id, force_new } = req.body as {
        content?: string;
        ticket_id?: string;
        force_new?: boolean;
      };
      const result = await portalService.postInboundFromCompanyUser({
        io: fastify.io,
        log: fastify.log,
        userId: req.user!.sub,
        companyId: cid,
        content: content ?? '',
        ticketId: ticket_id,
        forceNew: force_new === true,
      });
      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' });
    }
  });
}
