import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { createServerSupabaseClient } from '@/lib/supabase-server'

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params
  try {
    const supabase = await createServerSupabaseClient()
    const { data: { user: supabaseUser }, error: authError } = await supabase.auth.getUser()

    if (authError || !supabaseUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Check if user is admin
    const user = await prisma.user.findUnique({
      where: { id: supabaseUser.id },
      select: { isAdmin: true }
    })

    if (!user?.isAdmin) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    // Update prompt permissions back to private (rejected)
    const updatedPrompt = await prisma.prompt.update({
      where: { id },
      data: {
        permissions: 'private',
        visibility: null,
        updatedAt: new Date()
      }
    })

    return NextResponse.json({ 
      message: 'Prompt rejected successfully',
      prompt: updatedPrompt 
    })

  } catch (error) {
    console.error('Error rejecting prompt:', error)
    return NextResponse.json(
      { error: 'Failed to reject prompt' },
      { status: 500 }
    )
  }
}