/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Class API endpoints for single class operations
 * Part of: kreatiVortex - Platform Pembelajaran Tari Online
 */

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { auth } from '@/lib/auth';
import { headers } from 'next/headers';
import { getOrCreateUserProfile } from '@/lib/profile';

export async function GET(
  _: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    });

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Get or create user profile
    const userProfile = await getOrCreateUserProfile(session.user.id);

    const { id } = await params;
    
    // Build where clause based on user role
    let whereClause: any = {
      id,
      isActive: true,
    };

    if (userProfile.role.name === 'ADMIN' || userProfile.role.name === 'PENDIDIK') {
      // Admins and Educators can see any active class
      whereClause.OR = [
        { educatorId: userProfile.id },
        { 
          members: {
            some: {
              studentId: userProfile.id
            }
          }
        }
      ];
    } else if (userProfile.role.name === 'CALON_PENDIDIK') {
      // Students can only see classes they're enrolled in
      whereClause.members = {
        some: {
          studentId: userProfile.id
        }
      };
    } else {
      // UMUM role cannot access any class
      return NextResponse.json(
        { success: false, message: 'Access denied' },
        { status: 403 }
      );
    }

    const classData = await prisma.class.findUnique({
      where: whereClause,
      include: {
        educator: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
        members: {
          include: {
            student: {
              include: {
                user: {
                  select: {
                    name: true,
                    image: true,
                  },
                },
              },
            },
          },
        },
        videos: true,
        assignments: true,
      },
    });

    if (!classData) {
      return NextResponse.json(
        { success: false, message: 'Class not found or access denied' },
        { status: 404 }
      );
    }

    return NextResponse.json({ success: true, data: classData });
  } catch (error) {
    console.error('Error fetching class:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to fetch class' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  _: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    await prisma.class.delete({
      where: { id },
    });

    return NextResponse.json({ success: true, message: 'Class deleted' });
  } catch (error) {
    console.error('Error deleting class:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to delete class' },
      { status: 500 }
    );
  }
}