/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Class API endpoints for listing and creating classes
 * 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: Request) {
  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 { searchParams } = new URL(request.url);
    const educatorId = searchParams.get('educatorId');

    // If educatorId is provided and matches current user, show classes they created
    if (educatorId && educatorId === userProfile.id) {
      const classes = await prisma.class.findMany({
        where: { educatorId: userProfile.id, isActive: true },
        include: {
          educator: {
            include: {
              user: {
                select: {
                  name: true,
                  image: true,
                },
              },
            },
          },
          _count: {
            select: { members: true },
          },
        },
        orderBy: {
          createdAt: 'desc',
        },
      });

      return NextResponse.json({ success: true, data: classes });
    }

    // Otherwise, show classes based on user role
    let classes: any[] = [];
    
    if (userProfile.role.name === 'UMUM') {
      // General users can't see any classes
      classes = [];
    } else if (userProfile.role.name === 'CALON_PENDIDIK') {
      // Students can only see classes they've joined
      classes = await prisma.class.findMany({
        where: {
          isActive: true,
          members: {
            some: {
              studentId: userProfile.id
            }
          }
        },
        include: {
          educator: {
            include: {
              user: {
                select: {
                  name: true,
                  image: true,
                },
              },
            },
          },
          _count: {
            select: { members: true },
          },
        },
        orderBy: {
          createdAt: 'desc',
        },
      });
    } else {
      // Educators and Admins can see all classes
      classes = await prisma.class.findMany({
        where: {
          isActive: true,
        },
        include: {
          educator: {
            include: {
              user: {
                select: {
                  name: true,
                  image: true,
                },
              },
            },
          },
          _count: {
            select: { members: true },
          },
        },
        orderBy: {
          createdAt: 'desc',
        },
      });
    }

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

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, description, code, maxStudents } = body;

    // Validation
    if (!name || !code) {
      return NextResponse.json(
        { success: false, message: 'Name and Code are required' },
        { status: 400 }
      );
    }

    // Mock educator ID for now
    const educator = await prisma.userProfile.findFirst();
    
    if (!educator) {
      return NextResponse.json(
        { success: false, message: 'No user profile found' },
        { status: 400 }
      );
    }

    const newClass = await prisma.class.create({
      data: {
        name,
        description,
        code,
        maxStudents: maxStudents ? Number(maxStudents) : null,
        educatorId: educator.id,
        createdBy: educator.id,
        updatedBy: educator.id,
      },
    });

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