import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';
import { isValidId } from '@/lib/validation';

export async function GET(request: NextRequest) {
  try {
    // Auth check
    const authResult = await verifyAdminPermission(request, 'canManageCommunity');
    if ('error' in authResult) return authResult.error;

    const posts = await db.communityPost.findMany({
      orderBy: { createdAt: 'desc' },
      include: { user: { select: { name: true, email: true } } },
    });

    return NextResponse.json({ success: true, posts });
  } catch (error) {
    console.error('Admin community fetch error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch posts' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // Auth check
    const authResult = await verifyAdminPermission(request, 'canManageCommunity');
    if ('error' in authResult) return authResult.error;

    const { id } = await request.json();

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Post ID is required' },
        { status: 400 }
      );
    }

    if (!isValidId(id)) {
      return NextResponse.json(
        { success: false, error: 'Invalid post ID format' },
        { status: 400 }
      );
    }

    await db.communityPost.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Admin community delete error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to delete post' },
      { status: 500 }
    );
  }
}
