/**
 * @ai-summary Fastify routes for documents API
 */
import { FastifyInstance, FastifyPluginAsync, FastifyPluginOptions } from 'fastify';
import { DocumentsController } from './documents.controller';
// Note: Validation uses TypeScript types at handler level; follow existing repo pattern (no JSON schema registration)

export const documentsRoutes: FastifyPluginAsync = async (
  fastify: FastifyInstance,
  _opts: FastifyPluginOptions
) => {
  const ctrl = new DocumentsController();
  const requireAuth = fastify.authenticate.bind(fastify);

  fastify.get('/documents', {
    preHandler: [requireAuth],
    handler: ctrl.list.bind(ctrl)
  });

  fastify.get<{ Params: any }>('/documents/:id', {
    preHandler: [requireAuth],
    handler: ctrl.get.bind(ctrl)
  });

  fastify.get<{ Params: any }>('/documents/vehicle/:vehicleId', {
    preHandler: [requireAuth],
    handler: async (req, reply) => {
      const userId = (req as any).user?.sub as string;
      const query = { vehicleId: (req.params as any).vehicleId };
      const docs = await ctrl['service'].listDocuments(userId, query);
      return reply.code(200).send(docs);
    }
  });

  fastify.post<{ Body: any }>('/documents', {
    preHandler: [requireAuth],
    handler: ctrl.create.bind(ctrl)
  });

  fastify.put<{ Params: any; Body: any }>('/documents/:id', {
    preHandler: [requireAuth],
    handler: ctrl.update.bind(ctrl)
  });

  fastify.delete<{ Params: any }>('/documents/:id', {
    preHandler: [requireAuth],
    handler: ctrl.remove.bind(ctrl)
  });

  fastify.post<{ Params: any }>('/documents/:id/upload', {
    preHandler: [requireAuth],
    handler: ctrl.upload.bind(ctrl)
  });

  fastify.get<{ Params: any }>('/documents/:id/download', {
    preHandler: [requireAuth],
    handler: ctrl.download.bind(ctrl)
  });
};
