import { FastifyInstance } from 'fastify';
import { runCodeQualityCheck } from './repository.js';
import { CodeQualityCheckParamsSchema } from './types.js';
import { requireAdmin } from '../../lib/auth.js';

export async function codeQualityRoutes(fastify: FastifyInstance) {
  // Run code quality check.
  // Admin-only: this route shells out (`npm run typecheck/lint/build/test:run`)
  // in a caller-supplied `projectPath` and is therefore privileged. See the
  // "Privilege Surface" section in `dashboard/DEPLOYMENT.md`.
  fastify.post('/code-quality/check', {
    preHandler: async (req) => requireAdmin(req),
  }, async (request, reply) => {
    try {
      const params = CodeQualityCheckParamsSchema.parse(request.body);
      const report = await runCodeQualityCheck(params);
      return reply.send(report);
    } catch (error) {
      fastify.log.error(error, 'Failed to run code quality check');
      return reply.code(500).send({ error: 'Failed to run code quality check' });
    }
  });
}
