import { NextRequest, NextResponse } from 'next/server'

/**
 * POST /api/admin/companion/lesson
 * Start a new lesson session
 * Proxy to backend /api/classroom/sessions
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'

    // TODO: Replace with actual backend call
    // const response = await fetch(`${backendUrl}/api/classroom/sessions`, {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json',
    //   },
    //   body: JSON.stringify(body),
    // })
    //
    // if (!response.ok) {
    //   throw new Error(`Backend responded with ${response.status}`)
    // }
    //
    // const data = await response.json()
    // return NextResponse.json(data)

    // Mock response - create a new session
    const sessionId = `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`

    const mockSession = {
      success: true,
      data: {
        sessionId,
        classId: body.classId,
        className: body.className || body.classId,
        subject: body.subject,
        topic: body.topic,
        startTime: new Date().toISOString(),
        phases: [
          { phase: 'einstieg', duration: 8, status: 'active', actualTime: 0 },
          { phase: 'erarbeitung', duration: 20, status: 'planned', actualTime: 0 },
          { phase: 'sicherung', duration: 10, status: 'planned', actualTime: 0 },
          { phase: 'transfer', duration: 7, status: 'planned', actualTime: 0 },
          { phase: 'reflexion', duration: 5, status: 'planned', actualTime: 0 },
        ],
        totalPlannedDuration: 50,
        currentPhaseIndex: 0,
        elapsedTime: 0,
        isPaused: false,
        pauseDuration: 0,
        overtimeMinutes: 0,
        status: 'in_progress',
        homeworkList: [],
        materials: [],
      },
    }

    return NextResponse.json(mockSession)
  } catch (error) {
    console.error('Start lesson error:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

/**
 * GET /api/admin/companion/lesson
 * Get current lesson session or list of recent sessions
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const sessionId = searchParams.get('sessionId')

    // TODO: Replace with actual backend call
    // const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'
    // const url = sessionId
    //   ? `${backendUrl}/api/classroom/sessions/${sessionId}`
    //   : `${backendUrl}/api/classroom/sessions`
    //
    // const response = await fetch(url)
    // const data = await response.json()
    // return NextResponse.json(data)

    // Mock response
    if (sessionId) {
      return NextResponse.json({
        success: true,
        data: null, // No active session stored on server in mock
      })
    }

    return NextResponse.json({
      success: true,
      data: {
        sessions: [], // Empty list for now
      },
    })
  } catch (error) {
    console.error('Get lesson error:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

/**
 * PATCH /api/admin/companion/lesson
 * Update lesson session (timer state, phase changes, etc.)
 */
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json()
    const { sessionId, ...updates } = body

    if (!sessionId) {
      return NextResponse.json(
        { success: false, error: 'Session ID required' },
        { status: 400 }
      )
    }

    // TODO: Replace with actual backend call
    // const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'
    // const response = await fetch(`${backendUrl}/api/classroom/sessions/${sessionId}`, {
    //   method: 'PATCH',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(updates),
    // })
    //
    // const data = await response.json()
    // return NextResponse.json(data)

    // Mock response - just acknowledge the update
    return NextResponse.json({
      success: true,
      message: 'Session updated',
    })
  } catch (error) {
    console.error('Update lesson error:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

/**
 * DELETE /api/admin/companion/lesson
 * End/delete a lesson session
 */
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const sessionId = searchParams.get('sessionId')

    if (!sessionId) {
      return NextResponse.json(
        { success: false, error: 'Session ID required' },
        { status: 400 }
      )
    }

    // TODO: Replace with actual backend call

    return NextResponse.json({
      success: true,
      message: 'Session ended',
    })
  } catch (error) {
    console.error('End lesson error:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}
