/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-12-01
 * Purpose: Forum posts API endpoints for creating posts within forums
 * Part of: kreatiVortex - Platform Pembelajaran Tari Online
 */

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function POST(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { title, content } = body;

    // Validation
    if (!content) {
      return NextResponse.json(
        { success: false, message: 'Content is required' },
        { status: 400 }
      );
    }

    // Mock author for now - in real app, get from session
    const author = await prisma.userProfile.findFirst();
    
    if (!author) {
      return NextResponse.json(
        { success: false, message: 'No user profile found' },
        { status: 400 }
      );
    }

    // Check if forum exists
    const forum = await prisma.forum.findUnique({
      where: { id },
    });

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

    const post = await prisma.forumPost.create({
      data: {
        title: title || `Re: ${forum.title}`,
        content,
        forumId: id,
        authorId: author.id,
        updatedBy: author.id,
      },
      include: {
        author: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
      },
    });

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