import { NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { getCurrentAdmin, AdminPermission, hasPermission } from '@/lib/admin-auth';

export const runtime = 'nodejs';

export async function GET(request: Request) {
  try {
    const admin = await getCurrentAdmin(request as any);
    if (!admin || !hasPermission(admin, AdminPermission.DELETE_CONTENT)) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '0');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
    const search = url.searchParams.get('search') || '';
    const category = url.searchParams.get('category') || '';
    const status = url.searchParams.get('status') || 'all';

    // Build where clause for filtering
    const where: any = {};
    if (search) {
      where.OR = [
        { title: { contains: search, mode: 'insensitive' } },
        { description: { contains: search, mode: 'insensitive' } },
        { author: { contains: search, mode: 'insensitive' } }
      ];
    }
    if (category && category !== 'all') {
      where.category = category;
    }
    if (status !== 'all') {
      where.isActive = status === 'active';
    }

    // Get total count for pagination
    const total = await prisma.prayerRequest.count({ where });

    // Get prayer requests with pagination
    const prayerRequests = await prisma.prayerRequest.findMany({
      where,
      select: {
        id: true,
        title: true,
        description: true,
        category: true,
        author: true,
        isAnonymous: true,
        isPublic: true,
        language: true,
        prayerCount: true,
        isActive: true,
        createdAt: true,
        updatedAt: true,
        user: {
          select: {
            id: true,
            email: true,
            name: true
          }
        }
      },
      orderBy: { createdAt: 'desc' },
      skip: page * pageSize,
      take: pageSize
    });

    return NextResponse.json({
      prayerRequests,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      }
    });

  } catch (error) {
    console.error('Admin prayer requests list error:', error);
    return NextResponse.json(
      { error: 'Server error' },
      { status: 500 }
    );
  }
}
