// app/api/revalidate/route.ts
// Manual cache revalidation endpoint
import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';

export async function POST(request: NextRequest) {
  try {
    // Authentication
    const apiSecret = request.headers.get('X-API-Secret');
    const expectedSecret = process.env.SYNC_API_SECRET;

    if (!apiSecret || apiSecret !== expectedSecret) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Get paths to revalidate from request body
    const { paths } = await request.json();

    if (!paths || !Array.isArray(paths)) {
      // Default: revalidate all main pages
      revalidatePath('/', 'page');
      revalidatePath('/blogs', 'page');
      
      return NextResponse.json({
        success: true,
        message: 'Default paths revalidated',
        revalidated: ['/', '/blogs']
      });
    }

    // Revalidate specified paths
    for (const path of paths) {
      revalidatePath(path, 'page');
    }

    return NextResponse.json({
      success: true,
      message: 'Paths revalidated successfully',
      revalidated: paths
    });

  } catch (error) {
    console.error('Revalidation error:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Revalidation failed',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}
