// /src/app/admin/server/page.tsx
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'
import { NextRequest } from 'next/server'
import Card from '../components/Card'
import ServerView from '../components/admin/server/ServerView'

export const dynamic = 'force-dynamic'

async function ensureConfig() {
  const cfg = await prisma.serverConfig.upsert({
    where: { id: 'default' },
    update: {},
    create: {
      id: 'default',
      serverIp: '',
      serverPassword: '',                 // ⬅️ neu
      pterodactylServerId: '',
      pterodactylServerApiKey: '',
    },
  })
  return cfg
}

export default async function AdminServerPage(req: NextRequest) {
  const session = await getServerSession(authOptions(req))
  const me = session?.user as any | undefined

  if (!me?.steamId || !me?.isAdmin) {
    redirect('/')
  }

  const [cfg, meUser] = await Promise.all([
    ensureConfig(),
    prisma.user.findUnique({
      where: { steamId: me.steamId },
      select: { steamId: true, pterodactylClientApiKey: true, name: true },
    }),
  ])

  async function save(formData: FormData) {
    'use server'

    const serverIp       = String(formData.get('serverIp') ?? '').trim()
    const serverId       = String(formData.get('serverId') ?? '').trim()
    const serverApiKey   = String(formData.get('serverApiKey') ?? '').trim()
    const serverPassword = String(formData.get('serverPassword') ?? '').trim() // ⬅️ neu
    const clientApiKey   = String(formData.get('clientApiKey') ?? '').trim()

    if (!serverIp) throw new Error('Server-IP darf nicht leer sein.')
    if (!serverId) throw new Error('Pterodactyl Server-ID darf nicht leer sein.')

    await prisma.$transaction(async (tx) => {
      await tx.serverConfig.update({
        where: { id: 'default' },
        data: {
          serverIp,
          pterodactylServerId: serverId,
          ...(serverApiKey   ? { pterodactylServerApiKey: serverApiKey } : {}),
          ...(serverPassword ? { serverPassword } : {}), // ⬅️ nur setzen, wenn übergeben
        },
      })

      if (clientApiKey) {
        await tx.user.update({
          where: { steamId: me?.steamId },
          data: { pterodactylClientApiKey: clientApiKey },
        })
      }
    })

    revalidatePath('/admin/server')
  }

  return (
    <Card title="Serververwaltung" description="Hier kannst du die Servereinstellungen ändern" maxWidth="auto">
      <ServerView
        cfg={cfg}
        meUser={meUser}
        meSteamId={me.steamId}
        onSave={save}
      />
    </Card>
  )
}
