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

// GET /api/courses/[id]
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    await dbConnect();
    const { id } = await params;
    const course = await Course.findById(id).populate('parentCourse', 'title level slug');
    if (!course) {
      return NextResponse.json({ success: false, error: 'Course not found' }, { status: 404 });
    }

    const user = getAuthUser(req);
    const isAdmin = user && (user.role === 'admin' || user.role === 'super_admin');

    // If course is unpublished and user is not admin, deny access
    if (!course.isPublished && !isAdmin) {
      return NextResponse.json({ success: false, error: 'Course is not currently available' }, { status: 404 });
    }

    let isEnrolled = false;
    let subscription: any = null;

    if (user && user.role === 'student') {
      subscription = await Subscription.findOne({
        student: user.id,
        course: course._id,
        status: { $in: ['active', 'manually_extended'] },
        expiryDate: { $gt: new Date() },
      });
      if (subscription) {
        isEnrolled = true;
      }
    }

    const courseObj: any = course.toObject();

    // If neither admin nor enrolled student, strip video streaming IDs and direct file URLs
    if (!isAdmin && !isEnrolled && Array.isArray(courseObj.chapters)) {
      courseObj.chapters = courseObj.chapters.map((ch: any) => ({
        _id: ch._id,
        chapterNumber: ch.chapterNumber,
        title: ch.title,
        description: ch.description,
        durationMinutes: ch.durationMinutes,
        isDownloadableScriptActive: ch.isDownloadableScriptActive,
        isDownloadableHomeworkActive: ch.isDownloadableHomeworkActive,
        order: ch.order,
      }));
    }

    return NextResponse.json({
      success: true,
      course: courseObj,
      isEnrolled,
      subscriptionId: subscription?._id || null,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching course' },
      { status: 500 }
    );
  }
}

// PUT /api/courses/[id] - Admin updates course
export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

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

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

    if (body.title) course.title = body.title;
    if (body.level) course.level = body.level;
    if (body.courseType) course.courseType = body.courseType;
    if (body.description !== undefined) course.description = body.description;
    if (body.parentCourse !== undefined) course.parentCourse = body.parentCourse || null;
    if (body.regularPrice !== undefined) course.regularPrice = Number(body.regularPrice);
    if (body.offerPrice !== undefined) {
      course.offerPrice = body.offerPrice !== null ? Number(body.offerPrice) : undefined;
    }
    if (body.currency) course.currency = body.currency;
    if (body.isPublished !== undefined) course.isPublished = Boolean(body.isPublished);
    if (body.validityMonths !== undefined) course.validityMonths = Number(body.validityMonths);
    if (body.requireChapterCompletionForDownload !== undefined) {
      course.requireChapterCompletionForDownload = Boolean(body.requireChapterCompletionForDownload);
    }
    if (Array.isArray(body.chapters)) {
      course.chapters = body.chapters.map((ch: any) => ({
        ...ch,
        videoReference: extractFilename(ch.videoReference),
        scriptFileUrl: extractFilename(ch.scriptFileUrl),
        homeworkFileUrl: extractFilename(ch.homeworkFileUrl),
      }));
    }
    if (body.thumbnailUrl !== undefined) course.thumbnailUrl = extractFilename(body.thumbnailUrl);

    await course.save();

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

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

// DELETE /api/courses/[id] - Admin deletes course
export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

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

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