/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Forum API endpoints for listing and creating forums
 * 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(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type');
    const classId = searchParams.get('classId');

    const whereClause: any = { isActive: true };
    
    if (type) {
      whereClause.type = type;
    }
    
    if (classId) {
      whereClause.classId = classId;
    }

    const forums = await prisma.forum.findMany({
      where: whereClause,
      include: {
        creator: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
        _count: {
          select: { posts: true },
        },
      },
      orderBy: {
        updatedAt: 'desc',
      },
    });

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

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 { title, description, type, classId, attachments } = body;

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

    const forum = await prisma.forum.create({
      data: {
        title,
        description,
        type: type || 'GENERAL',
        classId,
        createdBy: userProfile.id,
        updatedBy: userProfile.id,
      },
    });

    // Create the first post in the forum
    if (description || attachments) {
      await prisma.forumPost.create({
        data: {
          title,
          content: description || '',
          forumId: forum.id,
          authorId: userProfile.id,
          updatedBy: userProfile.id,
          attachments: attachments || [],
        },
      });
    }

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