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

// GET: 강좌 목록 조회
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '13');
    const curriculumId = searchParams.get('curriculumId');
    const skip = (page - 1) * limit;

    const where = curriculumId ? { curriculumId } : {};

    const [lectures, total] = await Promise.all([
      prisma.lecture.findMany({
        where,
        skip,
        take: limit,
        orderBy: {
          registeredAt: 'desc',
        },
        include: {
          curriculum: {
            select: {
              title: true,
            },
          },
          registrant: {
            select: {
              name: true,
            },
          },
        },
      }),
      prisma.lecture.count({ where }),
    ]);

    return NextResponse.json({
      data: lectures.map((lecture) => ({
        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,
      })),
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Error fetching lectures:', error);
    return NextResponse.json(
      { error: '강좌 목록을 불러오는 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

// POST: 강좌 생성
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { title, curriculumId, registrantId, attachmentFile, evaluationQuestionCount, thumbnailImage } = body;

    if (!title || !curriculumId || !registrantId) {
      return NextResponse.json(
        { error: '강좌명, 교육 과정 ID, 등록자 ID는 필수입니다.' },
        { status: 400 }
      );
    }

    // 교육 과정 존재 확인
    const curriculum = await prisma.curriculum.findUnique({
      where: { id: curriculumId },
    });

    if (!curriculum) {
      return NextResponse.json(
        { error: '유효한 교육 과정을 선택해주세요.' },
        { status: 400 }
      );
    }

    // 등록자 존재 확인
    const registrant = await prisma.user.findUnique({
      where: { id: registrantId },
    });

    if (!registrant) {
      return NextResponse.json(
        { error: '유효한 등록자를 선택해주세요.' },
        { status: 400 }
      );
    }

    const lecture = await prisma.lecture.create({
      data: {
        title,
        curriculumId,
        registrantId,
        attachmentFile: attachmentFile || null,
        evaluationQuestionCount: evaluationQuestionCount || 0,
        thumbnailImage: thumbnailImage || null,
      },
      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,
      },
    }, { status: 201 });
  } catch (error) {
    console.error('Error creating lecture:', error);
    return NextResponse.json(
      { error: '강좌 생성 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

