import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth } from "@/lib/auth";

export async function GET(request: NextRequest) {
  try {
    const auth = await requireAuth(request);
    const userId = auth?.userId;

    const courses = await prisma.learnCourse.findMany({
      where: { published: true },
      orderBy: { createdAt: "desc" },
    });

    // If authenticated, fetch the user's enrollments for the returned courses
    let enrollmentsMap = new Map<string, { progress: number; completed: boolean }>();
    if (userId && courses.length > 0) {
      const enrollments = await prisma.learnEnrollment.findMany({
        where: {
          userId,
          courseId: { in: courses.map((c) => c.id) },
        },
        select: { courseId: true, progress: true, completed: true },
      });
      for (const e of enrollments) {
        enrollmentsMap.set(e.courseId, { progress: e.progress, completed: e.completed });
      }
    }

    const result = courses.map((course) => {
      const enrollment = enrollmentsMap.get(course.id);
      return {
        id: course.id,
        slug: course.slug,
        title: course.title,
        author: course.author,
        description: course.description,
        imageUrl: course.imageUrl,
        moduleCount: course.moduleCount,
        totalMinutes: course.totalMinutes,
        difficulty: course.difficulty,
        priceFlh: course.priceFlh,
        priceUsd: course.priceUsd,
        subscriptionOnly: course.subscriptionOnly,
        enrolled: userId ? !!enrollment : null,
        ...(enrollment ? { enrollment: { progress: enrollment.progress, completed: enrollment.completed } } : {}),
      };
    });

    return NextResponse.json({ courses: result });
  } catch (error) {
    console.error("GET /api/learn/courses error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
