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

interface Params {
  params: { id: string };
}

// POST /api/courses/[id]/download
// Body: { chapterId: string, resourceType: 'script' | 'homework' }
export async function POST(req: NextRequest, { params }: Params) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const body = await req.json();
    const { chapterId, resourceType } = body;

    if (!chapterId || !resourceType || !['script', 'homework'].includes(resourceType)) {
      return NextResponse.json(
        { success: false, error: 'Valid chapterId and resourceType ("script" | "homework") are required' },
        { status: 400 }
      );
    }

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

    const chapter = course.chapters.find((ch: any) => ch._id.toString() === chapterId);
    if (!chapter) {
      return NextResponse.json({ success: false, error: 'Chapter not found in this course' }, { status: 404 });
    }

    // Check if the resource download button is enabled by admin
    if (resourceType === 'script' && !chapter.isDownloadableScriptActive) {
      return NextResponse.json(
        { success: false, error: 'Script download is not enabled for this lesson' },
        { status: 403 }
      );
    }

    if (resourceType === 'homework' && !chapter.isDownloadableHomeworkActive) {
      return NextResponse.json(
        { success: false, error: 'Homework download is not enabled for this lesson' },
        { status: 403 }
      );
    }

    // Admin can always preview/download without enrollment check
    const isAdmin = auth.user.role === 'admin' || auth.user.role === 'super_admin';
    if (!isAdmin) {
      // Verify student subscription
      const subscription = await Subscription.findOne({
        student: auth.user.id,
        course: course._id,
        status: { $in: ['active', 'manually_extended'] },
      });

      if (!subscription) {
        return NextResponse.json(
          { success: false, error: 'You are not enrolled in this course' },
          { status: 403 }
        );
      }

      if (new Date() > subscription.expiryDate) {
        return NextResponse.json(
          { success: false, error: 'Your access to this course has expired' },
          { status: 403 }
        );
      }

      // Check chapter completion gating (PDF Requirement)
      if (course.requireChapterCompletionForDownload) {
        const isChapterCompleted = subscription.completedChapters.some(
          (c) => c.chapterId.toString() === chapterId
        );

        if (!isChapterCompleted) {
          return NextResponse.json(
            {
              success: false,
              isCompleted: false,
              error: 'Please complete the chapter to download script and homework with marking system',
            },
            { status: 403 }
          );
        }
      }
    }

    // Return the authorized resource link
    const rawFileRef = resourceType === 'script' ? chapter.scriptFileUrl : chapter.homeworkFileUrl;

    if (!rawFileRef) {
      return NextResponse.json(
        { success: false, error: `No ${resourceType} file has been uploaded for this lesson yet` },
        { status: 404 }
      );
    }

    const downloadUrl = getMediaUrl(rawFileRef, 'pdfs');

    return NextResponse.json({
      success: true,
      message: `${resourceType === 'script' ? 'Script' : 'Homework'} download link generated`,
      downloadUrl,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error processing download request' },
      { status: 500 }
    );
  }
}
