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

// GET /api/courses - List courses with filters
export async function GET(req: NextRequest) {
  try {
    await dbConnect();
    const { searchParams } = new URL(req.url);
    const level = searchParams.get('level');
    const courseType = searchParams.get('courseType');
    const user = getAuthUser(req);
    const isAdmin = user && (user.role === 'admin' || user.role === 'super_admin');

    const query: Record<string, any> = {};

    // Non-admins can only see published courses (PDF: B1/B2 remain hidden until admin enables them)
    if (!isAdmin) {
      query.isPublished = true;
    } else {
      const isPublishedParam = searchParams.get('isPublished');
      if (isPublishedParam !== null) {
        query.isPublished = isPublishedParam === 'true';
      }
    }

    const search = searchParams.get('search')?.trim();
    if (level && level !== 'all') query.level = level;
    if (courseType && courseType !== 'all') query.courseType = courseType;
    if (search) {
      const regex = new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
      query.$or = [{ title: regex }, { description: regex }, { level: regex }];
    }

    const courses = await Course.find(query)
      .populate('parentCourse', 'title level slug')
      .sort({ level: 1, 'chapters.order': 1, createdAt: 1 });

    // Clean sensitive streaming references from public listing
    const sanitizedCourses = courses.map((course) => {
      const courseObj: any = course.toObject();
      if (!isAdmin && 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 courseObj;
    });

    return NextResponse.json({
      success: true,
      count: sanitizedCourses.length,
      courses: sanitizedCourses,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching courses' },
      { status: 500 }
    );
  }
}

// POST /api/courses - Admin creates a new course / level / sub-course / lesson
export async function POST(req: NextRequest) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

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

    const { isValid, errorResponse } = validateFields(body, [
      'courseType',
      'title',
      'slug',
      'regularPrice',
    ]);
    if (!isValid) return errorResponse;

    const existingSlug = await Course.findOne({ slug: body.slug.toLowerCase().trim() });
    if (existingSlug) {
      return NextResponse.json(
        { success: false, error: 'A course with this slug already exists' },
        { status: 409 }
      );
    }

    const newCourse = await Course.create({
      level: body.level,
      courseType: body.courseType,
      title: body.title,
      slug: body.slug.toLowerCase().trim(),
      description: body.description || '',
      parentCourse: body.parentCourse || null,
      regularPrice: Number(body.regularPrice),
      offerPrice: body.offerPrice !== undefined && body.offerPrice !== null ? Number(body.offerPrice) : null,
      currency: body.currency || 'EUR',
      isPublished: Boolean(body.isPublished),
      validityMonths: body.validityMonths ? Number(body.validityMonths) : 4,
      requireChapterCompletionForDownload: body.requireChapterCompletionForDownload !== undefined
        ? Boolean(body.requireChapterCompletionForDownload)
        : true,
      chapters: Array.isArray(body.chapters)
        ? body.chapters.map((ch: any) => ({
            ...ch,
            videoReference: extractFilename(ch.videoReference),
            scriptFileUrl: extractFilename(ch.scriptFileUrl),
            homeworkFileUrl: extractFilename(ch.homeworkFileUrl),
          }))
        : [],
      thumbnailUrl: extractFilename(body.thumbnailUrl),
    });

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