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

const createPrayerSchema = z.object({
  title: z.string().min(1).max(200),
  description: z.string().min(1).max(1000),
  category: z.enum(['personal', 'family', 'health', 'work', 'ministry', 'world']),
  isAnonymous: z.boolean().optional().default(false)
})

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const category = searchParams.get('category')
    const limit = parseInt(searchParams.get('limit') || '20')
    const userId = searchParams.get('userId')

    // Build the where clause
    const where: any = {
      isActive: true
    }

    if (category && category !== 'all') {
      where.category = category
    }

    // Fetch prayers from database with user prayer status
    const prayers = await prisma.prayerRequest.findMany({
      where,
      take: limit,
      orderBy: {
        createdAt: 'desc'
      },
      include: {
        user: {
          select: {
            name: true
          }
        },
        userPrayers: userId ? {
          where: {
            userId: userId
          }
        } : false
      }
    })

    // Format prayers for response
    const formattedPrayers = prayers.map(prayer => ({
      id: prayer.id,
      title: prayer.title,
      description: prayer.description,
      category: prayer.category,
      author: prayer.isAnonymous ? 'Anonim' : prayer.author,
      timestamp: prayer.createdAt,
      prayerCount: prayer.prayerCount,
      isPrayedFor: userId && prayer.userPrayers ? prayer.userPrayers.length > 0 : false
    }))

    return NextResponse.json({
      success: true,
      prayers: formattedPrayers,
      total: formattedPrayers.length
    })
  } catch (error) {
    console.error('Error fetching prayers:', error)
    return NextResponse.json(
      {
        success: false,
        error: 'Failed to fetch prayers',
        prayers: []
      },
      { status: 500 }
    )
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const validatedData = createPrayerSchema.parse(body)

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

    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
        userName = session.user.name || 'Anonim'
      }
    }

    // Create new prayer in database
    const newPrayer = await prisma.prayerRequest.create({
      data: {
        title: validatedData.title,
        description: validatedData.description,
        category: validatedData.category,
        author: validatedData.isAnonymous ? 'Anonim' : userName,
        isAnonymous: validatedData.isAnonymous,
        userId: validatedData.isAnonymous ? null : userId,
        prayerCount: 0,
        isActive: true
      }
    })

    return NextResponse.json({
      success: true,
      prayer: {
        id: newPrayer.id,
        title: newPrayer.title,
        description: newPrayer.description,
        category: newPrayer.category,
        author: newPrayer.author,
        timestamp: newPrayer.createdAt,
        prayerCount: newPrayer.prayerCount,
        isPrayedFor: false
      },
      message: 'Prayer request submitted successfully'
    }, { status: 201 })
  } catch (error) {
    console.error('Error creating prayer:', error)

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        {
          success: false,
          error: 'Invalid prayer data',
          details: error.errors
        },
        { status: 400 }
      )
    }

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