import type { FastifyPluginAsync } from 'fastify'
import { LookupCreateSchema, LookupUpdateSchema } from '@lunarfront/shared/schemas'
import { UnitStatusService, ItemConditionService } from '../../services/lookup.service.js'
import { ConflictError, ValidationError } from '../../lib/errors.js'

function createLookupRoutes(prefix: string, service: typeof UnitStatusService) {
  const routes: FastifyPluginAsync = async (app) => {
    app.get(`/${prefix}`, { preHandler: [app.authenticate, app.requirePermission('inventory.view')] }, async (request, reply) => {
      const data = await service.list(app.db)
      return reply.send({ data })
    })

    app.post(`/${prefix}`, { preHandler: [app.authenticate, app.requirePermission('inventory.admin')] }, async (request, reply) => {
      const parsed = LookupCreateSchema.safeParse(request.body)
      if (!parsed.success) {
        throw new ValidationError('Validation failed', parsed.error.flatten())
      }

      const existing = await service.getBySlug(app.db, parsed.data.slug)
      if (existing) {
        throw new ConflictError(`Slug "${parsed.data.slug}" already exists`)
      }

      const row = await service.create(app.db, parsed.data)
      return reply.status(201).send(row)
    })

    app.patch(`/${prefix}/:id`, { preHandler: [app.authenticate, app.requirePermission('inventory.admin')] }, async (request, reply) => {
      const { id } = request.params as { id: string }
      const parsed = LookupUpdateSchema.safeParse(request.body)
      if (!parsed.success) {
        throw new ValidationError('Validation failed', parsed.error.flatten())
      }
      const row = await service.update(app.db, id, parsed.data)
      if (!row) return reply.status(404).send({ error: { message: 'Not found', statusCode: 404 } })
      return reply.send(row)
    })

    app.delete(`/${prefix}/:id`, { preHandler: [app.authenticate, app.requirePermission('inventory.admin')] }, async (request, reply) => {
      const { id } = request.params as { id: string }
      const row = await service.delete(app.db, id)
      if (!row) return reply.status(404).send({ error: { message: 'Not found', statusCode: 404 } })
      return reply.send(row)
    })
  }
  return routes
}

export const lookupRoutes: FastifyPluginAsync = async (app) => {
  await app.register(createLookupRoutes('unit-statuses', UnitStatusService))
  await app.register(createLookupRoutes('item-conditions', ItemConditionService))
}
