import type { FastifyPluginAsync } from 'fastify'
import { PaginationSchema, RegisterCreateSchema, RegisterUpdateSchema } from '@lunarfront/shared/schemas'
import { RegisterService } from '../../services/register.service.js'

export const registerRoutes: FastifyPluginAsync = async (app) => {
  app.post('/registers', { preHandler: [app.authenticate, app.requirePermission('pos.edit')] }, async (request, reply) => {
    const parsed = RegisterCreateSchema.safeParse(request.body)
    if (!parsed.success) {
      return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
    }
    const register = await RegisterService.create(app.db, parsed.data)
    return reply.status(201).send(register)
  })

  app.get('/registers', { preHandler: [app.authenticate, app.requirePermission('pos.view')] }, async (request, reply) => {
    const query = request.query as Record<string, string | undefined>
    const params = PaginationSchema.parse(query)
    const result = await RegisterService.list(app.db, params, { locationId: query.locationId })
    return reply.send(result)
  })

  app.get('/registers/all', { preHandler: [app.authenticate, app.requirePermission('pos.view')] }, async (request, reply) => {
    const query = request.query as Record<string, string | undefined>
    const data = await RegisterService.listAll(app.db, query.locationId)
    return reply.send({ data })
  })

  app.get('/registers/:id', { preHandler: [app.authenticate, app.requirePermission('pos.view')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const register = await RegisterService.getById(app.db, id)
    if (!register) return reply.status(404).send({ error: { message: 'Register not found', statusCode: 404 } })
    return reply.send(register)
  })

  app.patch('/registers/:id', { preHandler: [app.authenticate, app.requirePermission('pos.edit')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const parsed = RegisterUpdateSchema.safeParse(request.body)
    if (!parsed.success) {
      return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
    }
    const register = await RegisterService.update(app.db, id, parsed.data)
    return reply.send(register)
  })

  app.delete('/registers/:id', { preHandler: [app.authenticate, app.requirePermission('pos.admin')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const register = await RegisterService.delete(app.db, id)
    return reply.send(register)
  })
}
