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

// GET /api/results — Get user's academic results
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl
    const userId = searchParams.get('userId') || ''

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

    const results = await db.academicResult.findMany({
      where: { userId },
      orderBy: [{ year: 'desc' }, { term: 'desc' }],
    })

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

// POST /api/results — Add or update academic result
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, year, term, subject, result } = body

    if (!userId || !year || !term || !subject || result === undefined) {
      return NextResponse.json(
        { error: 'Missing required fields: userId, year, term, subject, result' },
        { status: 400 }
      )
    }

    if (year < 2020 || year > 2030) {
      return NextResponse.json({ error: 'Invalid year' }, { status: 400 })
    }
    if (term < 1 || term > 4) {
      return NextResponse.json({ error: 'Term must be between 1 and 4' }, { status: 400 })
    }
    if (result < 0 || result > 100) {
      return NextResponse.json({ error: 'Result must be between 0 and 100' }, { status: 400 })
    }

    // Upsert: check if result already exists for this year/term/subject
    const existing = await db.academicResult.findFirst({
      where: { userId, year, term, subject },
    })

    let academicResult
    if (existing) {
      academicResult = await db.academicResult.update({
        where: { id: existing.id },
        data: { result },
      })
    } else {
      academicResult = await db.academicResult.create({
        data: { userId, year, term, subject, result },
      })
    }

    return NextResponse.json({
      result: academicResult,
      message: existing ? 'Result updated successfully' : 'Result added successfully',
    })
  } catch (error) {
    console.error('Error saving result:', error)
    return NextResponse.json({ error: 'Failed to save result' }, { status: 500 })
  }
}
