import { getServerSession } from 'next-auth'
import { redirect } from 'next/navigation'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import SettingsClient from './SettingsClient'

export const metadata = {
  title: 'Configurações | LexMind',
  description: 'Gerencie seu perfil, assinatura, chaves de API e segurança',
}

export default async function ConfiguracoesPage() {
  const session = await getServerSession(authOptions)
  if (!session?.user) redirect('/login')

  const [user, apiKeys, subscription, storageData] = await Promise.all([
    prisma.user.findUnique({
      where: { id: session.user.id },
      select: {
        id: true,
        name: true,
        email: true,
        phone: true,
        oabNumber: true,
        oabState: true,
        avatar: true,
        plan: true,
        credits: true,
        createdAt: true,
      },
    }),
    prisma.apiKey.findMany({
      where: { userId: session.user.id },
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        name: true,
        key: true,
        active: true,
        createdAt: true,
      },
    }),
    prisma.subscription.findFirst({
      where: { userId: session.user.id, status: 'ACTIVE' },
      orderBy: { startDate: 'desc' },
    }),
    (async () => {
      const [agg, count] = await Promise.all([
        prisma.upload.aggregate({
          where: { userId: session.user.id },
          _sum: { size: true },
        }),
        prisma.upload.count({ where: { userId: session.user.id } }),
      ])
      const limits: Record<string, number> = {
        FREE: 1073741824, STARTER: 1073741824,
        PRO: 5368709120, ENTERPRISE: 21474836480,
      }
      const userPlan = (await prisma.user.findUnique({ where: { id: session.user.id }, select: { plan: true } }))?.plan || 'FREE'
      return {
        used: agg._sum.size || 0,
        limit: limits[userPlan] || limits.FREE,
        count,
      }
    })(),
  ])

  if (!user) redirect('/login')

  const maskedKeys = apiKeys.map((k) => ({
    ...k,
    key: k.key.slice(0, 8) + '••••••••' + k.key.slice(-4),
    createdAt: k.createdAt.toISOString(),
  }))

  return (
    <SettingsClient
      user={{
        ...user,
        createdAt: user.createdAt.toISOString(),
      }}
      apiKeys={maskedKeys}
      subscription={
        subscription
          ? {
              plan: subscription.plan,
              status: subscription.status,
              startDate: subscription.startDate.toISOString(),
              endDate: subscription.endDate?.toISOString() ?? null,
            }
          : null
      }
      storage={{
        used: storageData.used,
        limit: storageData.limit,
        count: storageData.count,
      }}
    />
  )
}
