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 { extractFilename } from '@/lib/media';

// GET /api/lessons/[id]
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    await dbConnect();
    const lesson = await Lesson.findById(params.id).populate('course', 'title level courseType');
    if (!lesson) {
      return NextResponse.json({ success: false, error: 'Lesson not found' }, { status: 404 });
    }
    return NextResponse.json({ success: true, lesson });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error' },
      { status: 500 }
    );
  }
}

// PATCH /api/lessons/[id]
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

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

    const lesson = await Lesson.findById(params.id);
    if (!lesson) {
      return NextResponse.json({ success: false, error: 'Lesson not found' }, { status: 404 });
    }

    if (body.title !== undefined) lesson.title = body.title;
    if (body.course !== undefined) lesson.course = body.course;
    if (body.chapterNumber !== undefined) lesson.chapterNumber = Number(body.chapterNumber);
    if (body.description !== undefined) lesson.description = body.description;
    if (body.videoReference !== undefined) lesson.videoReference = extractFilename(body.videoReference);
    if (body.durationMinutes !== undefined) lesson.durationMinutes = Number(body.durationMinutes);
    if (body.price !== undefined) lesson.price = Number(body.price);
    if (body.isDownloadableScriptActive !== undefined) lesson.isDownloadableScriptActive = Boolean(body.isDownloadableScriptActive);
    if (body.scriptFileUrl !== undefined) lesson.scriptFileUrl = extractFilename(body.scriptFileUrl);
    if (body.isDownloadableHomeworkActive !== undefined) lesson.isDownloadableHomeworkActive = Boolean(body.isDownloadableHomeworkActive);
    if (body.homeworkFileUrl !== undefined) lesson.homeworkFileUrl = extractFilename(body.homeworkFileUrl);
    if (body.order !== undefined) lesson.order = Number(body.order);

    await lesson.save();

    // Also update in parent course chapters array if present
    if (lesson.course) {
      const course = await Course.findById(lesson.course);
      if (course) {
        const chapterIdx = course.chapters.findIndex((ch: any) => String(ch._id) === String(lesson._id));
        if (chapterIdx !== -1) {
          course.chapters[chapterIdx] = {
            _id: lesson._id,
            chapterNumber: lesson.chapterNumber,
            title: lesson.title,
            description: lesson.description,
            videoReference: lesson.videoReference,
            durationMinutes: lesson.durationMinutes,
            isDownloadableScriptActive: lesson.isDownloadableScriptActive,
            scriptFileUrl: lesson.scriptFileUrl,
            isDownloadableHomeworkActive: lesson.isDownloadableHomeworkActive,
            homeworkFileUrl: lesson.homeworkFileUrl,
            order: lesson.order,
          };
          await course.save();
        }
      }
    }

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

// PUT alias for PATCH
export const PUT = PATCH;

// DELETE /api/lessons/[id]
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const lesson = await Lesson.findByIdAndDelete(params.id);
    if (!lesson) {
      return NextResponse.json({ success: false, error: 'Lesson not found' }, { status: 404 });
    }

    // Remove from course's chapters array
    if (lesson.course) {
      const course = await Course.findById(lesson.course);
      if (course) {
        course.chapters = course.chapters.filter((ch: any) => String(ch._id) !== String(lesson._id));
        await course.save();
      }
    }

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