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 userId = searchParams.get('userId');
    const lectureId = searchParams.get('lectureId');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '100');
    const skip = (page - 1) * limit;

    const where: any = {};
    if (userId) where.userId = userId;
    if (lectureId) where.lectureId = lectureId;

    const [userLectures, total] = await Promise.all([
      prisma.userLecture.findMany({
        where,
        skip,
        take: limit,
        orderBy: {
          enrolledAt: 'desc',
        },
        include: {
          user: {
            select: {
              id: true,
              name: true,
              email: true,
            },
          },
          lecture: {
            include: {
              curriculum: {
                select: {
                  title: true,
                },
              },
            },
          },
        },
      }),
      prisma.userLecture.count({ where }),
    ]);

    return NextResponse.json({
      data: userLectures.map((ul) => ({
        id: ul.id,
        userId: ul.userId,
        userName: ul.user.name,
        userEmail: ul.user.email,
        lectureId: ul.lectureId,
        lectureName: ul.lecture.title,
        courseName: ul.lecture.curriculum.title,
        enrolledAt: ul.enrolledAt.toISOString().split('T')[0],
        completedAt: ul.completedAt ? ul.completedAt.toISOString().split('T')[0] : null,
        isCompleted: ul.isCompleted,
        progress: ul.progress,
        score: ul.score,
      })),
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Error fetching user lectures:', error);
    return NextResponse.json(
      { error: '수강 관계 목록을 불러오는 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

// POST: 사용자-강좌 수강 관계 생성 (수강 신청)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userId, lectureId } = body;

    if (!userId || !lectureId) {
      return NextResponse.json(
        { error: '사용자 ID와 강좌 ID는 필수입니다.' },
        { status: 400 }
      );
    }

    // 사용자 존재 확인
    const user = await prisma.user.findUnique({
      where: { id: userId },
    });

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

    // 강좌 존재 확인
    const lecture = await prisma.lecture.findUnique({
      where: { id: lectureId },
    });

    if (!lecture) {
      return NextResponse.json(
        { error: '유효한 강좌를 선택해주세요.' },
        { status: 400 }
      );
    }

    // 이미 수강 중인지 확인
    const existing = await prisma.userLecture.findUnique({
      where: {
        userId_lectureId: {
          userId,
          lectureId,
        },
      },
    });

    if (existing) {
      return NextResponse.json(
        { error: '이미 수강 중인 강좌입니다.' },
        { status: 400 }
      );
    }

    const userLecture = await prisma.userLecture.create({
      data: {
        userId,
        lectureId,
      },
      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,
      },
    }, { status: 201 });
  } catch (error) {
    console.error('Error creating user lecture:', error);
    return NextResponse.json(
      { error: '수강 신청 중 오류가 발생했습니다.' },
      { status: 500 }
    );
  }
}

