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 phoneNumber = searchParams.get('phoneNumber')
    const fromDate = searchParams.get('fromDate')
    const toDate = searchParams.get('toDate')

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

    if (status) where.status = status
    if (phoneNumber) where.phoneNumber = { contains: phoneNumber }
    if (fromDate || toDate) {
      where.createdAt = {}
      if (fromDate) (where.createdAt as Record<string, unknown>).gte = new Date(fromDate)
      if (toDate) (where.createdAt as Record<string, unknown>).lte = new Date(toDate)
    }

    const [logs, total] = await Promise.all([
      db.whatsAppLog.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.whatsAppLog.count({ where }),
    ])

    // Status summary
    const statusSummary = await db.whatsAppLog.groupBy({
      by: ['status'],
      _count: true,
    })

    return NextResponse.json({
      success: true,
      data: {
        logs,
        statusSummary: statusSummary.map((s) => ({ status: s.status, count: s._count })),
        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 { phoneNumber, message, template } = body

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

    const log = await db.whatsAppLog.create({
      data: {
        phoneNumber,
        message,
        template: template || '',
        status: 'PENDING',
      },
    })

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