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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const status = searchParams.get('status')
    const priority = searchParams.get('priority')
    const userId = searchParams.get('userId')
    const assignedTo = searchParams.get('assignedTo')

    const where: Record<string, unknown> = {}

    if (status) where.status = status
    if (priority) where.priority = priority
    if (userId) where.userId = userId
    if (assignedTo) where.assignedTo = assignedTo

    const [tickets, total] = await Promise.all([
      db.ticket.findMany({
        where,
        include: {
          user: { select: { id: true, name: true, email: true, phone: true } },
          _count: { select: { replies: true } },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.ticket.count({ where }),
    ])

    return NextResponse.json({
      success: true,
      data: {
        tickets,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, subject, description, priority, assignedTo } = body

    if (!userId || !subject || !description) {
      return NextResponse.json(
        { success: false, error: 'userId, subject, and description are required' },
        { status: 400 }
      )
    }

    const ticket = await db.ticket.create({
      data: {
        userId,
        subject,
        description,
        priority: priority || 'MEDIUM',
        status: 'OPEN',
        assignedTo: assignedTo || null,
      },
      include: {
        user: { select: { id: true, name: true, email: true } },
      },
    })

    return NextResponse.json({ success: true, data: ticket }, { status: 201 })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
