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

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

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

    return NextResponse.json({
      data: {
        id: lecture.id,
        courseName: lecture.curriculum.title,
        lectureName: lecture.title,
        attachedFile: lecture.attachmentFile || '없음',
        questionCount: lecture.evaluationQuestionCount,
        registrar: lecture.registrant.name || '알 수 없음',
        createdAt: lecture.registeredAt.toISOString().split('T')[0],
        curriculumId: lecture.curriculumId,
        thumbnailImage: lecture.thumbnailImage,
      },
    });
  } catch (error) {
    console.error('Error fetching 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 { title, attachmentFile, evaluationQuestionCount, thumbnailImage } = body;

    const lecture = await prisma.lecture.update({
      where: { id: params.id },
      data: {
        ...(title && { title }),
        ...(attachmentFile !== undefined && { attachmentFile }),
        ...(evaluationQuestionCount !== undefined && { evaluationQuestionCount }),
        ...(thumbnailImage !== undefined && { thumbnailImage }),
      },
      include: {
        curriculum: {
          select: {
            title: true,
          },
        },
        registrant: {
          select: {
            name: true,
          },
        },
      },
    });

    return NextResponse.json({
      data: {
        id: lecture.id,
        courseName: lecture.curriculum.title,
        lectureName: lecture.title,
        attachedFile: lecture.attachmentFile || '없음',
        questionCount: lecture.evaluationQuestionCount,
        registrar: lecture.registrant.name || '알 수 없음',
        createdAt: lecture.registeredAt.toISOString().split('T')[0],
        curriculumId: lecture.curriculumId,
        thumbnailImage: lecture.thumbnailImage,
      },
    });
  } catch (error) {
    console.error('Error updating lecture:', error);
    return NextResponse.json(
      { error: '강좌 수정 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

// DELETE: 강좌 삭제
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    await prisma.lecture.delete({
      where: { id: params.id },
    });

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

