import { revalidatePath } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request) {
  // 1. 从请求头中获取密钥
  const secret = request.headers.get('x-revalidate-secret');

  // 2. 验证密钥
  if (secret !== process.env.REVALIDATE_TOKEN) {
    return NextResponse.json({ message: 'Invalid token' }, { status: 401 });
  }

  // 3. 从请求体中获取需要重新验证的路径
  const body = await request.json();
  const { path } = body;

  if (!path) {
    return NextResponse.json({ message: 'Path is required' }, { status: 400 });
  }

  try {
    // 4. 调用 Next.js 的 revalidatePath 函数
    revalidatePath(path);
    return NextResponse.json({ revalidated: true, now: Date.now() });
  } catch (error) {
    // 5. 如果发生错误，返回错误信息
    return NextResponse.json(
      { message: 'Error revalidating', error: error.message },
      { status: 500 }
    );
  }
} 