/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-12-05
 * Purpose: Toggle comment privacy API endpoint for educators
 * 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 PATCH(
  _: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    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);

    // Get the comment to update
    const comment = await prisma.comment.findUnique({
      where: { id },
      include: {
        forumPost: {
          include: {
            forum: {
              include: {
                class: {
                  include: {
                    educator: true
                  }
                }
              }
            }
          }
        }
      }
    });

    if (!comment) {
      return NextResponse.json(
        { success: false, message: 'Comment not found' },
        { status: 404 }
      );
    }

    // Check if user is educator of the class
    const classEducator = comment.forumPost?.forum?.class?.educator;
    if (!classEducator || userProfile.id !== classEducator.id) {
      return NextResponse.json(
        { success: false, message: 'Only class educators can toggle comment privacy' },
        { status: 403 }
      );
    }

    // Toggle privacy
    const newPrivacyState = !comment.isPrivate;
    const privateForId = newPrivacyState ? comment.forumPost?.authorId : null;

    const updatedComment = await prisma.comment.update({
      where: { id },
      data: {
        isPrivate: newPrivacyState,
        privateForId: privateForId,
        updatedBy: userProfile.id,
      },
      include: {
        author: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
      },
    });

    return NextResponse.json({ 
      success: true, 
      data: updatedComment,
      message: `Comment is now ${newPrivacyState ? 'private' : 'public'}`
    });
  } catch (error) {
    console.error('Error toggling comment privacy:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to toggle comment privacy' },
      { status: 500 }
    );
  }
}