import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Lesson } from '@/models/Lesson';
import { Course } from '@/models/Course';
import { requireAdmin } from '@/lib/auth';
import { validateFields } from '@/lib/validation';
import { extractFilename } from '@/lib/media';

// GET /api/lessons - List lessons (optionally filtered by courseId)
export async function GET(req: NextRequest) {
  try {
    await dbConnect();
    const { searchParams } = new URL(req.url);
    const search = searchParams.get('search')?.trim();
    const courseId = searchParams.get('courseId');

    const query: Record<string, any> = {};
    if (courseId && courseId !== 'all') {
      const subCourses = await Course.find({ parentCourse: courseId }).select('_id');
      if (subCourses.length > 0) {
        const subIds = subCourses.map((sc) => sc._id);
        query.course = { $in: [courseId, ...subIds] };
      } else {
        query.course = courseId;
      }
    }
    if (search) {
      const regex = new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
      query.$or = [{ title: regex }, { description: regex }];
    }

    const lessons = await Lesson.find(query)
      .populate('course', 'title level courseType')
      .sort({ course: 1, order: 1, chapterNumber: 1, createdAt: 1 });

    return NextResponse.json({
      success: true,
      count: lessons.length,
      lessons,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching lessons' },
      { status: 500 }
    );
  }
}

// POST /api/lessons - Create a new standalone lesson assigned to a target Course/Sub-Course
export async function POST(req: NextRequest) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const body = await req.json();

    const { isValid, errorResponse } = validateFields(body, [
      'course',
      'title',
      'videoReference',
    ]);
    if (!isValid) return errorResponse;

    // Verify parent course exists
    const targetCourse = await Course.findById(body.course);
    if (!targetCourse) {
      return NextResponse.json(
        { success: false, error: 'Target course not found' },
        { status: 404 }
      );
    }

    const newLesson = await Lesson.create({
      course: body.course,
      chapterNumber: body.chapterNumber ? Number(body.chapterNumber) : 1,
      title: body.title,
      description: body.description || '',
      videoReference: extractFilename(body.videoReference),
      durationMinutes: body.durationMinutes ? Number(body.durationMinutes) : 0,
      price: body.price !== undefined ? Number(body.price) : 0,
      isDownloadableScriptActive: Boolean(body.isDownloadableScriptActive),
      scriptFileUrl: extractFilename(body.scriptFileUrl),
      isDownloadableHomeworkActive: Boolean(body.isDownloadableHomeworkActive),
      homeworkFileUrl: extractFilename(body.homeworkFileUrl),
      order: body.order ? Number(body.order) : 0,
    });

    // Sync lesson into course's chapters array for backward compatibility
    targetCourse.chapters.push({
      _id: newLesson._id,
      chapterNumber: newLesson.chapterNumber,
      title: newLesson.title,
      description: newLesson.description,
      videoReference: newLesson.videoReference,
      durationMinutes: newLesson.durationMinutes,
      isDownloadableScriptActive: newLesson.isDownloadableScriptActive,
      scriptFileUrl: newLesson.scriptFileUrl,
      isDownloadableHomeworkActive: newLesson.isDownloadableHomeworkActive,
      homeworkFileUrl: newLesson.homeworkFileUrl,
      order: newLesson.order,
    });
    await targetCourse.save();

    return NextResponse.json(
      {
        success: true,
        message: 'Lesson created successfully',
        lesson: newLesson,
      },
      { status: 201 }
    );
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error creating lesson' },
      { status: 500 }
    );
  }
}
