export function registerAuth(fastify) {
  function normalizeEmail(email) {
    return String(email || '').trim().toLowerCase()
  }

  fastify.decorate('verifyAdmin', async function verifyAdmin(request, reply) {
    const adminEmail = normalizeEmail(process.env.ADMIN_EMAIL)
    if (!adminEmail || !adminEmail.includes('@')) {
      return reply.code(503).send({ error: 'ADMIN_EMAIL не задан в .env' })
    }

    try {
      await request.jwtVerify()
    } catch {
      return reply.code(401).send({ error: 'Не авторизован' })
    }

    const userEmail = normalizeEmail(request.user?.email)
    if (userEmail !== adminEmail) {
      return reply.code(403).send({ error: 'Недостаточно прав' })
    }
  })
}
