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

// GET: 특정 교육 과정 조회
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const curriculum = await prisma.curriculum.findUnique({
      where: { id: params.id },
      include: {
        lectures: {
          orderBy: {
            registeredAt: 'desc',
          },
          include: {
            registrant: {
              select: {
                name: true,
              },
            },
          },
        },
      },
    });

    if (!curriculum) {
      return NextResponse.json(
        { error: '교육 과정을 찾을 수 없습니다.' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      data: {
        id: curriculum.id,
        courseName: curriculum.title,
        instructorId: curriculum.instructorId,
        thumbnailImage: curriculum.thumbnailImage,
        createdAt: curriculum.createdAt.toISOString().split('T')[0],
        lectures: curriculum.lectures.map((lecture) => ({
          id: lecture.id,
          lectureName: lecture.title,
          attachedFile: lecture.attachmentFile || '없음',
          questionCount: lecture.evaluationQuestionCount,
          registrar: lecture.registrant.name || '알 수 없음',
          createdAt: lecture.registeredAt.toISOString().split('T')[0],
        })),
      },
    });
  } catch (error) {
    console.error('Error fetching curriculum:', error);
    return NextResponse.json(
      { error: '교육 과정을 불러오는 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

// PUT: 교육 과정 수정
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json();
    const { title, instructorId, thumbnailImage } = body;

    const curriculum = await prisma.curriculum.update({
      where: { id: params.id },
      data: {
        ...(title && { title }),
        ...(instructorId && { instructorId }),
        ...(thumbnailImage !== undefined && { thumbnailImage }),
      },
      include: {
        lectures: {
          select: {
            id: true,
          },
        },
      },
    });

    return NextResponse.json({
      data: {
        id: curriculum.id,
        courseName: curriculum.title,
        instructorId: curriculum.instructorId,
        thumbnailImage: curriculum.thumbnailImage,
        createdAt: curriculum.createdAt.toISOString().split('T')[0],
        lectureCount: curriculum.lectures.length,
      },
    });
  } catch (error) {
    console.error('Error updating curriculum:', error);
    return NextResponse.json(
      { error: '교육 과정 수정 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

// DELETE: 교육 과정 삭제
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    await prisma.curriculum.delete({
      where: { id: params.id },
    });

    return NextResponse.json({ message: '교육 과정이 삭제되었습니다.' });
  } catch (error) {
    console.error('Error deleting curriculum:', error);
    return NextResponse.json(
      { error: '교육 과정 삭제 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

