/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Role registration API for kreatiVortex platform
 * 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 POST(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);

    // Check if user already has a specific role (not 'UMUM')
    if (userProfile.role.name !== 'UMUM') {
      return NextResponse.json(
        { success: false, message: 'User already has a role' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const { role, institution, className, teachingLevel, purpose, nim } = body;

    // Get role from database
    const targetRole = await prisma.userRole.findUnique({
      where: { name: role }
    });

    if (!targetRole) {
      return NextResponse.json(
        { success: false, message: 'Invalid role' },
        { status: 400 }
      );
    }

    // Validate required fields based on role
    if (role === 'PENDIDIK') {
      if (!institution || !className || !teachingLevel || !purpose) {
        return NextResponse.json(
          { success: false, message: 'All fields are required for educator registration' },
          { status: 400 }
        );
      }
    } else if (role === 'CALON_PENDIDIK') {
      if (!institution || !className || !nim) {
        return NextResponse.json(
          { success: false, message: 'All fields are required for student registration' },
          { status: 400 }
        );
      }

      // Check if class exists by code (not ID)
      const classExists = await prisma.class.findUnique({
        where: { code: className }
      });

      if (!classExists) {
        return NextResponse.json(
          { success: false, message: 'Class code not found. Please check the code with your educator.' },
          { status: 404 }
        );
      }
    }

    // Update user role and additional information
    const updatedProfile = await prisma.userProfile.update({
      where: { id: userProfile.id },
      data: {
        roleId: targetRole.id,
        nim: nim || null,
        bio: role === 'PENDIDIK' 
          ? `Institution: ${institution}\nTeaching Level: ${teachingLevel}\nPurpose: ${purpose}`
          : `Institution: ${institution}\nNIM: ${nim}`
      }
    });

    // If registering as student, add to class
    if (role === 'CALON_PENDIDIK') {
      // Find the class by code to get the ID
      const targetClass = await prisma.class.findUnique({
        where: { code: className }
      });

      if (targetClass) {
        await prisma.classMember.create({
          data: {
            classId: targetClass.id,
            studentId: updatedProfile.id,
            joinedAt: new Date()
          }
        });
      }
    }

    // If registering as educator, create the class
    if (role === 'PENDIDIK') {
      await prisma.class.create({
        data: {
          name: className,
          description: `Class created by ${updatedProfile.id}`,
          code: `CLASS-${Date.now()}`,
          educatorId: updatedProfile.id,
          createdBy: updatedProfile.id,
          updatedBy: updatedProfile.id,
          isActive: true
        }
      });
    }

    return NextResponse.json({ 
      success: true, 
      message: `Successfully registered as ${role}`,
      data: updatedProfile
    });

  } catch (error) {
    console.error('Error registering role:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to register role' },
      { status: 500 }
    );
  }
}