import type { FastifyPluginAsync } from 'fastify'
import { ModuleService } from '../../services/module.service.js'

export const moduleRoutes: FastifyPluginAsync = async (app) => {
  app.get('/modules', { preHandler: [app.authenticate, app.requirePermission('settings.view')] }, async (_request, reply) => {
    const modules = await ModuleService.listAll(app.db)
    return reply.send({ data: modules })
  })

  app.patch('/modules/:slug', { preHandler: [app.authenticate, app.requirePermission('settings.edit')] }, async (request, reply) => {
    const { slug } = request.params as { slug: string }
    const { enabled } = request.body as { enabled?: boolean }

    if (typeof enabled !== 'boolean') {
      return reply.status(400).send({ error: { message: 'enabled (boolean) is required', statusCode: 400 } })
    }

    try {
      const updated = await ModuleService.setEnabled(app.db, slug, enabled)
      if (!updated) return reply.status(404).send({ error: { message: 'Module not found', statusCode: 404 } })
      return reply.send(updated)
    } catch (err: any) {
      return reply.status(400).send({ error: { message: err.message, statusCode: 400 } })
    }
  })
}
