import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { requireAuth } from '@/lib/auth';
import { generateSecureStreamPresignedUrl } from '@/lib/s3';
import { Subscription } from '@/models/Subscription';

// GET /api/videos/secure-stream?fileKey=...&courseId=...
// Generates a temporary, encrypted GetObject S3 presigned URL for anti-download streaming
export async function GET(req: NextRequest) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const { searchParams } = new URL(req.url);
    const fileKey = searchParams.get('fileKey');
    const courseId = searchParams.get('courseId');

    if (!fileKey) {
      return NextResponse.json(
        { success: false, error: 'fileKey query parameter is required' },
        { status: 400 }
      );
    }

    const lessonId = searchParams.get('lessonId');

    const isAdmin = auth.user.role === 'admin' || auth.user.role === 'super_admin';

    // Verification: Non-admins must have an active subscription or purchase history for the course/lesson
    if (!isAdmin) {
      const allowedCourseIds: string[] = [];
      if (courseId) {
        allowedCourseIds.push(courseId);
        const { Course } = await import('@/models/Course');
        const targetCourse = await Course.findById(courseId);
        if (targetCourse?.parentCourse) {
          allowedCourseIds.push(targetCourse.parentCourse.toString());
        }
        const subCourses = await Course.find({ parentCourse: courseId }).select('_id');
        subCourses.forEach((sc) => allowedCourseIds.push(sc._id.toString()));
      }

      const query: Record<string, any> = {
        student: auth.user.id,
        status: 'active',
      };

      if (allowedCourseIds.length > 0) {
        query.course = { $in: allowedCourseIds };
      }

      const activeSubs = await Subscription.find(query);
      const hasValidSub = activeSubs.some((sub) => {
        if (!sub.isAccessValid()) return false;
        // If specific lessons array is defined and not empty, check if lessonId is included
        if (lessonId && sub.lessons && sub.lessons.length > 0) {
          return sub.lessons.some((lId: any) => lId.toString() === lessonId.toString());
        }
        return true;
      });

      if (!hasValidSub) {
        return NextResponse.json(
          { success: false, error: 'Access denied: Active course or lesson subscription required' },
          { status: 403 }
        );
      }
    }

    const baseUrl = process.env.NEXT_PUBLIC_API_URL ? process.env.NEXT_PUBLIC_API_URL : 'http://localhost:5000/api';
    const proxyStreamUrl = `${baseUrl}/videos/stream?key=${encodeURIComponent(fileKey)}`;
    return NextResponse.json({ success: true, streamUrl: proxyStreamUrl, fileKey, expiresInSeconds: 7200 });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to generate secure video stream URL' },
      { status: 500 }
    );
  }
}
