import { NextRequest, NextResponse } from 'next/server'

import { clickStorage } from '@/lib/click-storage'

export async function POST(request: NextRequest) {
  try {
    const body = await request.text()
    const { linkId, timestamp } = JSON.parse(body)

    // Записываем клик через общий storage
    const totalClicks = clickStorage.recordClick(linkId)

    console.warn(`API: Click tracked for ${linkId} at ${timestamp}. Total clicks: ${totalClicks}`)

    return NextResponse.json({
      success: true,
      linkId,
      timestamp,
      totalClicks,
    })
  } catch (error) {
    console.error('Error tracking click:', error)
    return NextResponse.json({ success: false, error: 'Failed to track click' }, { status: 500 })
  }
}

// API для получения статистики кликов
export async function GET(request: NextRequest) {
  try {
    const linkId = request.nextUrl.searchParams.get('linkId')

    if (linkId) {
      const clicks = clickStorage.getClicks(linkId)
      return NextResponse.json({ linkId, clicks })
    }

    // Возвращаем всю статистику
    const allStats = clickStorage.getAllClicks()
    return NextResponse.json(allStats)
  } catch (error) {
    console.error('Error getting click stats:', error)
    return NextResponse.json({ error: 'Failed to get click stats' }, { status: 500 })
  }
}
