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

// GET: 특정 수강 관계 조회
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const userLecture = await prisma.userLecture.findUnique({
      where: { id: params.id },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
        lecture: {
          include: {
            curriculum: {
              select: {
                title: true,
              },
            },
          },
        },
      },
    });

    if (!userLecture) {
      return NextResponse.json(
        { error: '수강 관계를 찾을 수 없습니다.' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      data: {
        id: userLecture.id,
        userId: userLecture.userId,
        userName: userLecture.user.name,
        userEmail: userLecture.user.email,
        lectureId: userLecture.lectureId,
        lectureName: userLecture.lecture.title,
        courseName: userLecture.lecture.curriculum.title,
        enrolledAt: userLecture.enrolledAt.toISOString().split('T')[0],
        completedAt: userLecture.completedAt ? userLecture.completedAt.toISOString().split('T')[0] : null,
        isCompleted: userLecture.isCompleted,
        progress: userLecture.progress,
        score: userLecture.score,
      },
    });
  } catch (error) {
    console.error('Error fetching user lecture:', 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 { progress, isCompleted, score } = body;

    const updateData: any = {};
    if (progress !== undefined) updateData.progress = Math.max(0, Math.min(100, progress));
    if (isCompleted !== undefined) {
      updateData.isCompleted = isCompleted;
      if (isCompleted && !body.completedAt) {
        updateData.completedAt = new Date();
      } else if (!isCompleted) {
        updateData.completedAt = null;
      }
    }
    if (score !== undefined) updateData.score = score;

    const userLecture = await prisma.userLecture.update({
      where: { id: params.id },
      data: updateData,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
        lecture: {
          include: {
            curriculum: {
              select: {
                title: true,
              },
            },
          },
        },
      },
    });

    return NextResponse.json({
      data: {
        id: userLecture.id,
        userId: userLecture.userId,
        userName: userLecture.user.name,
        userEmail: userLecture.user.email,
        lectureId: userLecture.lectureId,
        lectureName: userLecture.lecture.title,
        courseName: userLecture.lecture.curriculum.title,
        enrolledAt: userLecture.enrolledAt.toISOString().split('T')[0],
        completedAt: userLecture.completedAt ? userLecture.completedAt.toISOString().split('T')[0] : null,
        isCompleted: userLecture.isCompleted,
        progress: userLecture.progress,
        score: userLecture.score,
      },
    });
  } catch (error) {
    console.error('Error updating user lecture:', error);
    return NextResponse.json(
      { error: '수강 관계 수정 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

// DELETE: 수강 관계 삭제 (수강 취소)
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    await prisma.userLecture.delete({
      where: { id: params.id },
    });

    return NextResponse.json({ message: '수강이 취소되었습니다.' });
  } catch (error) {
    console.error('Error deleting user lecture:', error);
    return NextResponse.json(
      { error: '수강 취소 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

