/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: User profile 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 GET() {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    });

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

    const userProfile = await getOrCreateUserProfile(session.user.id);

    // Get full profile with user data
    const fullProfile = await prisma.userProfile.findUnique({
      where: { id: userProfile.id },
      include: { 
        role: true,
        user: {
          select: {
            name: true,
            email: true,
            image: true,
          }
        }
      }
    });

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

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