/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Comments API with file attachment support
 * 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);

    const body = await request.json();
    const { content, videoId, forumPostId, parentId, attachments } = body;

    // Validation
    if (!content && (!attachments || attachments.length === 0)) {
      return NextResponse.json(
        { success: false, message: 'Content or attachment is required' },
        { status: 400 }
      );
    }

    if (!videoId && !forumPostId) {
      return NextResponse.json(
        { success: false, message: 'Video ID or Forum Post ID is required' },
        { status: 400 }
      );
    }

    const comment = await prisma.comment.create({
      data: {
        content: content || '',
        videoId: videoId || null,
        forumPostId: forumPostId || null,
        parentId: parentId || null,
        authorId: userProfile.id,
        updatedBy: userProfile.id,
        attachments: attachments || [],
      },
      include: {
        author: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
      },
    });

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

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const videoId = searchParams.get('videoId');
    const forumPostId = searchParams.get('forumPostId');

    const whereClause: any = { isActive: true };
    
    if (videoId) {
      whereClause.videoId = videoId;
    }
    
    if (forumPostId) {
      whereClause.forumPostId = forumPostId;
    }

    const comments = await prisma.comment.findMany({
      where: whereClause,
      include: {
        author: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
        replies: {
          include: {
            author: {
              include: {
                user: {
                  select: {
                    name: true,
                    image: true,
                  },
                },
              },
            },
          },
          orderBy: {
            createdAt: 'asc',
          },
        },
      },
      orderBy: {
        createdAt: 'asc',
      },
    });

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