import type { FastifyInstance } from 'fastify';
import { authenticate, requireRole } from '../middleware/auth.js';
import { contactService } from '../services/contactService.js';
import { auditService } from '../services/auditService.js';

const staff = [authenticate, requireRole('admin', 'user')];

export async function contactRoutes(fastify: FastifyInstance) {
  fastify.get('/', { preHandler: staff }, async (_req, reply) => {
    return reply.send(await contactService.list());
  });

  fastify.get('/:id', { preHandler: staff }, async (req, reply) => {
    const { id } = req.params as { id: string };
    const detail = await contactService.getDetail(id);
    if (!detail) return reply.status(404).send({ error: 'Contact not found' });
    return reply.send(detail);
  });

  fastify.patch('/:id', { preHandler: staff }, async (req, reply) => {
    const { id } = req.params as { id: string };
    const { company_id } = req.body as { company_id?: string | null };
    if (!('company_id' in (req.body as object))) {
      return reply.status(400).send({ error: 'company_id is required (use null to unlink)' });
    }
    try {
      const contact = await contactService.setCompanyId(id, company_id ?? null);
      await auditService.log(req.user!.sub, 'user', 'contact.company_set', 'contact', id, {
        company_id: company_id ?? null,
      });
      const detail = await contactService.getDetail(id);
      return reply.send(detail ?? contact);
    } catch (e: unknown) {
      const err = e as { statusCode?: number; message?: string };
      return reply.status(err.statusCode ?? 500).send({ error: err.message ?? 'Error' });
    }
  });
}
