import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { qrInvoiceRequestSchema, type QRInvoiceRequestInput } from '../schemas/qr-invoice.schema.js';
import { qrBillService } from '../services/qr-bill.service.js';
import { ApiError } from '../errors/error-handler.js';

export async function invoiceRoutes(fastify: FastifyInstance): Promise<void> {
  fastify.post(
    '/api/v1/invoice/qr-bill',
    async (request: FastifyRequest<{ Body: QRInvoiceRequestInput }>, reply: FastifyReply) => {
      // Validierung mit Zod
      const parseResult = qrInvoiceRequestSchema.safeParse(request.body);

      if (!parseResult.success) {
        throw ApiError.validationError(
          parseResult.error.errors.map(e => ({
            path: e.path.join('.'),
            message: e.message,
          }))
        );
      }

      // PDF generieren
      const pdfBuffer = await qrBillService.generateQRBill(parseResult.data);

      // Response Headers setzen
      reply
        .header('Content-Type', 'application/pdf')
        .header('Content-Disposition', `attachment; filename="qr-bill-${Date.now()}.pdf"`)
        .header('Content-Length', pdfBuffer.length);

      return reply.send(pdfBuffer);
    }
  );
}
