import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

export const dynamic = 'force-dynamic'

export async function GET() {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) return NextResponse.json({ error: 'Não autenticado' }, { status: 401 })

  const [userWithProfile, spots, reviews] = await Promise.all([
    prisma.user.findUnique({
      where: { id: session.user.id },
      select: {
        id: true, name: true, email: true, role: true, image: true, createdAt: true,
        profile: true,
      },
    }),
    prisma.spot.findMany({
      where: { authorId: session.user.id },
      orderBy: { createdAt: 'desc' },
      select: { id: true, name: true, status: true, difficulty: true, createdAt: true, viewCount: true },
    }),
    prisma.review.findMany({
      where: { authorId: session.user.id },
      orderBy: { createdAt: 'desc' },
      select: {
        id: true, rating: true, body: true, status: true, createdAt: true,
        spot: { select: { id: true, name: true } },
      },
    }),
  ])

  return NextResponse.json({ user: userWithProfile, spots, reviews })
}

export async function PATCH(req: Request) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) return NextResponse.json({ error: 'Não autenticado' }, { status: 401 })

  const body = await req.json() as {
    name?: string
    bio?: string
    location?: string
    phone?: string
    website?: string
    instagram?: string
    droneEquipment?: string
    certA1A3?: boolean
    certA2?: boolean
    certSTS01?: boolean
    certSTS02?: boolean
    certLUC?: boolean
    droneClasses?: string[]
    hasInsurance?: boolean
    certNotes?: string
  }

  const { name, ...profileFields } = body

  // Update name on User if provided
  if (name !== undefined) {
    if (!name || name.trim().length < 2) {
      return NextResponse.json({ error: 'Nome inválido' }, { status: 400 })
    }
    await prisma.user.update({
      where: { id: session.user.id },
      data: { name: name.trim() },
    })
  }

  // Upsert UserProfile
  if (Object.keys(profileFields).length > 0) {
    const profileData = {
      bio: profileFields.bio,
      location: profileFields.location,
      phone: profileFields.phone,
      website: profileFields.website,
      instagram: profileFields.instagram,
      droneEquipment: profileFields.droneEquipment,
      certA1A3: profileFields.certA1A3,
      certA2: profileFields.certA2,
      certSTS01: profileFields.certSTS01,
      certSTS02: profileFields.certSTS02,
      certLUC: profileFields.certLUC,
      droneClasses: profileFields.droneClasses,
      hasInsurance: profileFields.hasInsurance,
      certNotes: profileFields.certNotes,
    }
    // Remove undefined fields
    const clean = Object.fromEntries(Object.entries(profileData).filter(([, v]) => v !== undefined))

    await prisma.userProfile.upsert({
      where: { userId: session.user.id },
      create: { userId: session.user.id, ...clean },
      update: clean,
    })
  }

  const updated = await prisma.user.findUnique({
    where: { id: session.user.id },
    select: { id: true, name: true, email: true, role: true, profile: true },
  })

  return NextResponse.json({ user: updated })
}
