import { NextResponse } from 'next/server'
import { prisma } from '@/lib/db'

export async function POST(
  request: Request,
  { params }: any
) {
  try {
    const prayerId = params.id

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

    // Get user from auth token if available
    const authHeader = request.headers.get('authorization')
    let userId: string | null = null

    if (authHeader && authHeader.startsWith('Bearer ')) {
      const token = authHeader.slice(7)
      // Verify token and get user
      const session = await prisma.session.findUnique({
        where: { token },
        include: { user: true }
      })

      if (session && session.expiresAt > new Date()) {
        userId = session.userId
      }
    }

    // Get client IP for anonymous counting
    const ip = request.headers.get('x-forwarded-for') ||
               request.headers.get('x-real-ip') ||
               'unknown'

    // Start a transaction to update both the prayer count and user prayer record
    const result = await prisma.$transaction(async (tx) => {
      // Check if prayer request exists
      const prayerRequest = await tx.prayerRequest.findUnique({
        where: { id: prayerId }
      })

      if (!prayerRequest) {
        throw new Error('Prayer request not found')
      }

      // If user is logged in, track user prayer
      if (userId) {
        // Check if user already prayed for this
        const existingUserPrayer = await tx.userPrayer.findUnique({
          where: {
            userId_requestId: {
              userId: userId,
              requestId: prayerId
            }
          }
        })

        if (!existingUserPrayer) {
          // Create user prayer record
          await tx.userPrayer.create({
            data: {
              userId: userId,
              requestId: prayerId
            }
          })

          // Increment prayer count
          await tx.prayerRequest.update({
            where: { id: prayerId },
            data: {
              prayerCount: {
                increment: 1
              }
            }
          })
        }
      } else {
        // For anonymous users, track by IP
        const existingPrayer = await tx.prayer.findUnique({
          where: {
            requestId_ipAddress: {
              requestId: prayerId,
              ipAddress: ip
            }
          }
        })

        if (!existingPrayer) {
          // Create anonymous prayer record
          await tx.prayer.create({
            data: {
              requestId: prayerId,
              ipAddress: ip
            }
          })

          // Increment prayer count
          await tx.prayerRequest.update({
            where: { id: prayerId },
            data: {
              prayerCount: {
                increment: 1
              }
            }
          })
        }
      }

      return prayerRequest
    })

    return NextResponse.json({
      success: true,
      message: 'Prayer count updated successfully',
      prayerCount: result.prayerCount + 1
    })
  } catch (error: any) {
    console.error('Error updating prayer count:', error)

    if (error.message === 'Prayer request not found') {
      return NextResponse.json(
        {
          success: false,
          error: 'Prayer request not found'
        },
        { status: 404 }
      )
    }

    return NextResponse.json(
      {
        success: false,
        error: 'Failed to update prayer count'
      },
      { status: 500 }
    )
  }
}
