import { NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { prisma } from '@/lib/db'
import { projectSchema } from '@/lib/validations'
import { getTenantFilter } from '@/lib/tenant'

export async function GET() {
  try {
    const user = await getSession()
    if (!user) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
    }

    // Tenant isolation: each user only sees their tenant's projects
    const tenantFilter = getTenantFilter(user)

    const projects = await (prisma as any).project.findMany({
      where: tenantFilter,
      orderBy: { updatedAt: 'desc' },
      include: {
        owner: {
          select: { id: true, name: true, email: true },
        },
        _count: {
          select: { features: true },
        },
      },
    })

    return NextResponse.json({ projects })
  } catch (error) {
    console.error('Error fetching projects:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const user = await getSession()
    if (!user) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
    }

    if (user.role === 'VIEWER') {
      return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
    }

    const body = await request.json()
    const validated = projectSchema.safeParse(body)
    
    if (!validated.success) {
      return NextResponse.json(
        { error: 'Ungültige Eingabedaten', details: validated.error.flatten() },
        { status: 400 }
      )
    }

    // Generate unique number per tenant/year/mode.
    // Einsatz: E-YYYY-NNNN · Übung: Ü-YYYY-NNNN (getrennte Zählung je Modus)
    const mode = validated.data.mode === 'UEBUNG' ? 'UEBUNG' : 'EINSATZ'
    const year = new Date().getFullYear()
    const einsatzPrefix = `${mode === 'UEBUNG' ? 'Ü' : 'E'}-${year}-`
    let einsatzNr = `${einsatzPrefix}0001`
    try {
      const lastProject = await (prisma as any).project.findFirst({
        where: {
          tenantId: user.tenantId || undefined,
          einsatzNr: { startsWith: einsatzPrefix },
        },
        orderBy: { einsatzNr: 'desc' },
        select: { einsatzNr: true },
      })
      if (lastProject?.einsatzNr) {
        const lastNum = parseInt(lastProject.einsatzNr.split('-').pop())
        if (!isNaN(lastNum)) einsatzNr = `${einsatzPrefix}${String(lastNum + 1).padStart(4, '0')}`
      }
    } catch {}

    // Always set tenantId from the logged-in user's tenant
    const project = await (prisma as any).project.create({
      data: {
        ...validated.data,
        mode,
        einsatzNr,
        ownerId: user.id,
        tenantId: user.tenantId || null,
        mapCenter: validated.data.mapCenter || { lng: 8.5417, lat: 47.3769 },
        mapZoom: validated.data.mapZoom || 15,
      },
    })

    return NextResponse.json({ project }, { status: 201 })
  } catch (error) {
    console.error('Error creating project:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
