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,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const admin = await getCurrentAdmin(request as any);
    if (!admin || !hasPermission(admin, AdminPermission.DELETE_CONTENT)) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { id } = await params;

    const prayerRequest = await prisma.prayerRequest.findUnique({
      where: { id },
      include: {
        user: {
          select: {
            id: true,
            email: true,
            name: true,
            role: true
          }
        },
        prayers: {
          select: {
            id: true,
            ipAddress: true,
            createdAt: true
          },
          orderBy: { createdAt: 'desc' },
          take: 10
        },
        userPrayers: {
          select: {
            id: true,
            createdAt: true,
            user: {
              select: {
                id: true,
                email: true,
                name: true
              }
            }
          },
          orderBy: { createdAt: 'desc' },
          take: 10
        }
      }
    });

    if (!prayerRequest) {
      return NextResponse.json(
        { error: 'Prayer request not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ prayerRequest });

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

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

    const { id } = await params;
    const body = await request.json();
    const { action, reason } = body;

    let updateData: any = {};

    switch (action) {
      case 'approve':
        updateData = { isActive: true };
        break;
      case 'reject':
        updateData = { isActive: false };
        break;
      default:
        return NextResponse.json(
          { error: 'Invalid action' },
          { status: 400 }
        );
    }

    const prayerRequest = await prisma.prayerRequest.update({
      where: { id },
      data: updateData,
      select: {
        id: true,
        title: true,
        isActive: true,
        user: {
          select: {
            email: true
          }
        }
      }
    });

    // TODO: Add audit log entry here in the future
    console.log(`Admin ${admin.email} performed action '${action}' on prayer request ${prayerRequest.title}${reason ? ` with reason: ${reason}` : ''}`);

    return NextResponse.json({ prayerRequest });

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

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

    const { id } = await params;

    const prayerRequest = await prisma.prayerRequest.findUnique({
      where: { id },
      select: { title: true, user: { select: { email: true } } }
    });

    if (!prayerRequest) {
      return NextResponse.json(
        { error: 'Prayer request not found' },
        { status: 404 }
      );
    }

    // Delete prayer request and all related data (CASCADE)
    await prisma.prayerRequest.delete({
      where: { id }
    });

    console.log(`Admin ${admin.email} deleted prayer request "${prayerRequest.title}"`);

    return NextResponse.json({ success: true });

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