import { NextRequest, NextResponse } from 'next/server';
import { addVisitor } from '@/lib/visitors';

export async function POST(request: NextRequest) {
  try {
    const { url, userAgent, referer } = await request.json();
    
    if (!url) {
      return NextResponse.json(
        { error: 'URL is required' },
        { 
          status: 400,
          headers: {
            'Cache-Control': 'no-store, no-cache, must-revalidate',
          },
        }
      );
    }
    
    addVisitor({
      url,
      timestamp: Date.now(),
      userAgent: userAgent || null,
      referer: referer || null,
    });
    
    return NextResponse.json(
      { success: true },
      {
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate',
        },
      }
    );
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to track visitor' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate',
        },
      }
    );
  }
}

