export const dynamic = 'force-dynamic'

import { NextResponse } from 'next/server'
import { prisma } from '@/lib/db'

// GET demo project data — no auth required
export async function GET() {
  try {
    // Find demo project ID from system settings
    const setting = await (prisma as any).systemSetting.findUnique({
      where: { key: 'demo_project_id' },
    })

    if (!setting?.value) {
      return NextResponse.json({ error: 'Keine Demo konfiguriert' }, { status: 404 })
    }

    const project = await (prisma as any).project.findUnique({
      where: { id: setting.value },
    })

    if (!project) {
      return NextResponse.json({ error: 'Demo-Projekt nicht gefunden' }, { status: 404 })
    }

    const [features, journalEntries, journalCheckItems, journalPendenzen] = await Promise.all([
      (prisma as any).feature.findMany({
        where: { projectId: project.id },
        orderBy: { createdAt: 'asc' },
      }),
      (prisma as any).journalEntry.findMany({
        where: { projectId: project.id },
        orderBy: [{ time: 'asc' }, { sortOrder: 'asc' }, { createdAt: 'asc' }],
      }).catch(() => []),
      (prisma as any).journalCheckItem.findMany({
        where: { projectId: project.id },
        orderBy: { sortOrder: 'asc' },
      }).catch(() => []),
      (prisma as any).journalPendenz.findMany({
        where: { projectId: project.id },
        orderBy: { sortOrder: 'asc' },
      }).catch(() => []),
    ])

    return NextResponse.json({
      project: {
        id: project.id,
        title: project.title,
        location: project.location,
        description: project.description,
        einsatzleiter: project.einsatzleiter || '',
        journalfuehrer: project.journalfuehrer || '',
        mapCenter: project.mapCenter || { lng: 8.2275, lat: 47.3497 },
        mapZoom: project.mapZoom || 15,
      },
      features: features.map((f: any) => ({
        id: f.id,
        type: f.type,
        geometry: f.geometry,
        properties: f.properties || {},
      })),
      journal: {
        entries: journalEntries,
        checkItems: journalCheckItems,
        pendenzen: journalPendenzen,
      },
    })
  } catch (error) {
    console.error('[Demo API] Error:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
