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

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

// PATCH /api/subscriptions/[id]/progress - Update playback timestamp and chapter completion
export async function PATCH(req: NextRequest, { params }: Params) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const body = await req.json();
    const { completedChapterId, lastWatchedChapterId, lastWatchedPositionSeconds } = body;

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

    // Ensure student owns subscription or user is admin
    if (auth.user.role === 'student' && subscription.student.toString() !== auth.user.id) {
      return NextResponse.json({ success: false, error: 'Forbidden' }, { status: 403 });
    }

    if (completedChapterId) {
      const alreadyCompleted = subscription.completedChapters.some(
        (c) => c.chapterId.toString() === completedChapterId
      );
      if (!alreadyCompleted) {
        subscription.completedChapters.push({
          chapterId: completedChapterId as any,
          completedAt: new Date(),
        });
      }
    }

    if (lastWatchedChapterId) {
      subscription.lastWatchedChapter = lastWatchedChapterId as any;
    }

    if (lastWatchedPositionSeconds !== undefined) {
      subscription.lastWatchedPositionSeconds = Number(lastWatchedPositionSeconds);
    }

    // Calculate percent based on course total chapters
    const course = await Course.findById(subscription.course);
    if (course && course.chapters.length > 0) {
      const completedCount = subscription.completedChapters.length;
      subscription.completedPercent = Math.min(
        100,
        Math.round((completedCount / course.chapters.length) * 100)
      );
    }

    await subscription.save();

    return NextResponse.json({
      success: true,
      message: 'Progress updated successfully',
      progress: {
        completedPercent: subscription.completedPercent,
        completedChapters: subscription.completedChapters,
        lastWatchedChapter: subscription.lastWatchedChapter,
        lastWatchedPositionSeconds: subscription.lastWatchedPositionSeconds,
      },
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error updating progress' },
      { status: 500 }
    );
  }
}
