import { normalizeEmail } from '../../lib/auth.js'
import { prisma } from '../../lib/prisma.js'

export async function registerAdminProfileRoutes(fastify) {
  fastify.get('/api/admin/profile', { preHandler: [fastify.verifyAdmin] }, async (request, reply) => {
    const userId = request.user.sub
    const user = await prisma.user.findUnique({ where: { id: userId } })
    if (!user) return reply.code(404).send({ error: 'Пользователь не найден' })
    return {
      id: user.id,
      email: user.email,
      displayName: user.displayName,
      avatar: user.avatar,
      avatarStyle: user.avatarStyle,
    }
  })

  fastify.get('/api/admin/avatar', async (request, reply) => {
    const adminEmail = normalizeEmail(process.env.ADMIN_EMAIL)
    if (!adminEmail || !adminEmail.includes('@')) return reply.code(404).send({ error: 'Администратор не найден' })

    const user = await prisma.user.findUnique({ where: { email: adminEmail } })
    if (!user) return reply.code(404).send({ error: 'Администратор не найден' })

    return {
      avatar: user.avatar,
      avatarStyle: user.avatarStyle,
    }
  })

  fastify.patch('/api/admin/profile', { preHandler: [fastify.verifyAdmin] }, async (request, reply) => {
    const userId = request.user.sub
    const nameRaw = request.body?.displayName
    const displayName =
      nameRaw === undefined ? undefined : nameRaw === null ? null : nameRaw === '' ? null : String(nameRaw).trim()
    const avatarRaw = request.body?.avatar
    const avatar = avatarRaw === null || avatarRaw === undefined ? undefined : String(avatarRaw).trim()
    const avatarStyleRaw = request.body?.avatarStyle
    const avatarStyle =
      avatarStyleRaw === null || avatarStyleRaw === undefined ? undefined : String(avatarStyleRaw).trim()

    if (displayName !== undefined && displayName !== null && displayName.length > 40)
      return reply.code(400).send({ error: 'Имя/ник максимум 40 символов' })
    if (avatar !== undefined && avatar.length > 200000) return reply.code(400).send({ error: 'Аватар слишком большой' })
    if (avatarStyle !== undefined && avatarStyle !== '' && avatarStyle.length > 30) {
      return reply.code(400).send({ error: 'Стиль аватара слишком длинный' })
    }

    const data = {}
    if (displayName !== undefined) {
      data.displayName = displayName && displayName.length ? displayName : null
    }
    if (avatar !== undefined) {
      data.avatar = avatar === '' ? null : avatar
    }
    if (avatarStyle !== undefined) {
      data.avatarStyle = avatarStyle === '' ? null : avatarStyle
    }

    const updated = await prisma.user.update({ where: { id: userId }, data })
    return {
      id: updated.id,
      email: updated.email,
      displayName: updated.displayName,
      avatar: updated.avatar,
      avatarStyle: updated.avatarStyle,
    }
  })
}
