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

// GET /api/competitions — List competitions with status filter
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl
    const status = searchParams.get('status') || ''

    const where: Record<string, unknown> = {}
    if (status) where.status = status

    const competitions = await db.competition.findMany({
      where,
      include: {
        sponsor: {
          select: {
            id: true,
            companyName: true,
            industry: true,
            sponsorshipTier: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
    })

    const formatted = competitions.map((c) => ({
      id: c.id,
      title: c.title,
      slug: c.slug,
      description: c.description,
      industry: c.industry,
      startDate: c.startDate,
      endDate: c.endDate,
      prizePool: c.prizePool,
      maxEntries: c.maxEntries,
      eligibilityGrades: JSON.parse(c.eligibilityGrades || '[]'),
      rules: c.rules,
      judgingCriteria: JSON.parse(c.judgingCriteria || '[]'),
      prizes: JSON.parse(c.prizes || '[]'),
      status: c.status,
      createdAt: c.createdAt,
      sponsor: c.sponsor,
    }))

    return NextResponse.json({ competitions: formatted, count: formatted.length })
  } catch (error) {
    console.error('Error fetching competitions:', error)
    return NextResponse.json({ error: 'Failed to fetch competitions' }, { status: 500 })
  }
}

// POST /api/competitions — Create competition (admin)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { title, description, sponsorId, industry, startDate, endDate, prizePool, maxEntries, eligibilityGrades, rules, judgingCriteria, prizes, status } = body

    if (!title) {
      return NextResponse.json({ error: 'Title is required' }, { status: 400 })
    }

    // Generate slug from title
    const slug = title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '')

    const competition = await db.competition.create({
      data: {
        title,
        slug,
        description,
        sponsorId,
        industry,
        startDate: startDate ? new Date(startDate) : null,
        endDate: endDate ? new Date(endDate) : null,
        prizePool,
        maxEntries,
        eligibilityGrades: JSON.stringify(eligibilityGrades || []),
        rules,
        judgingCriteria: JSON.stringify(judgingCriteria || []),
        prizes: JSON.stringify(prizes || []),
        status: status || 'upcoming',
      },
    })

    return NextResponse.json({ competition, message: 'Competition created successfully' })
  } catch (error) {
    console.error('Error creating competition:', error)
    return NextResponse.json({ error: 'Failed to create competition' }, { status: 500 })
  }
}
