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 skip = (page - 1) * limit;

    const [curriculums, total] = await Promise.all([
      prisma.curriculum.findMany({
        skip,
        take: limit,
        orderBy: {
          createdAt: 'desc',
        },
        include: {
          lectures: {
            select: {
              id: true,
            },
          },
        },
      }),
      prisma.curriculum.count(),
    ]);

    return NextResponse.json({
      data: curriculums.map((curriculum) => ({
        id: curriculum.id,
        courseName: curriculum.title,
        instructorId: curriculum.instructorId,
        thumbnailImage: curriculum.thumbnailImage,
        createdAt: curriculum.createdAt.toISOString().split('T')[0],
        lectureCount: curriculum.lectures.length,
      })),
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Error fetching curriculums:', error);
    return NextResponse.json(
      { error: '교육 과정 목록을 불러오는 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

// POST: 교육 과정 생성
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { title, instructorId, thumbnailImage } = body;

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

    // 강사 존재 확인
    const instructor = await prisma.user.findUnique({
      where: { id: instructorId },
    });

    if (!instructor || instructor.role !== 'INSTRUCTOR') {
      return NextResponse.json(
        { error: '유효한 강사를 선택해주세요.' },
        { status: 400 }
      );
    }

    const curriculum = await prisma.curriculum.create({
      data: {
        title,
        instructorId,
        thumbnailImage: thumbnailImage || null,
      },
      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,
      },
    }, { status: 201 });
  } catch (error) {
    console.error('Error creating curriculum:', error);
    return NextResponse.json(
      { error: '교육 과정 생성 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

