import { normalizeEmail } from './auth.js'
import { generateAvatar } from './generate-avatar.js'
import { prisma } from './prisma.js'

export async function ensureAdminUser() {
  const adminEmail = normalizeEmail(process.env.ADMIN_EMAIL)
  if (!adminEmail) return
  if (!adminEmail.includes('@')) {
    throw new Error('ADMIN_EMAIL должен быть валидным email')
  }

  const avatarUri = await generateAvatar(adminEmail)
  await prisma.user.upsert({
    where: { email: adminEmail },
    update: {},
    create: { email: adminEmail, avatar: avatarUri, avatarStyle: 'avataaars' },
  })

  // Ensure admin notification settings exist
  const existing = await prisma.adminNotificationSettings.findFirst()
  if (!existing) {
    await prisma.adminNotificationSettings.create({
      data: {
        emailEnabled: true,
        telegramEnabled: false,
        newOrder: true,
        newOrderMessage: true,
        newReview: true,
        authCodeDuplicate: false,
      },
    })
  }
}
