import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { getClicks, resetClicks } from '@/lib/clicks';

async function checkAuth() {
  const cookieStore = await cookies();
  const auth = cookieStore.get('admin-auth');
  return auth?.value === 'authenticated';
}

export async function GET() {
  if (!(await checkAuth())) {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { 
        status: 401,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }

  try {
    const clicks = getClicks();
    return NextResponse.json(clicks, {
      headers: {
        'Cache-Control': 'private, s-maxage=10, stale-while-revalidate=60',
      },
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to get clicks' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

export async function POST(request: NextRequest) {
  if (!(await checkAuth())) {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { 
        status: 401,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }

  try {
    const { action }: { action: string } = await request.json();
    
    if (action === 'reset') {
      resetClicks();
      return NextResponse.json(
        { success: true },
        {
          headers: {
            'Cache-Control': 'no-store, no-cache, must-revalidate, private',
          },
        }
      );
    }
    
    return NextResponse.json(
      { error: 'Invalid action' },
      { 
        status: 400,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to reset clicks' },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

