/* eslint-disable @typescript-eslint/no-explicit-any */
import { revalidatePath } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  try {
    // 1. Cookie átvétele a kérésből
    const cookie = request.headers.get('cookie') || '';

    // 2. Java backend lekérdezése (user jogosultság)
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/';
    const url = apiUrl.replace(/\/$/, '') + '/accessManagement/getAccessConfig';
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      Cookie: cookie,
    };
    if (process.env.NEXT_PUBLIC_ENV === 'test') {
      headers.Authorization =
        'Basic ' +
        Buffer.from(`${process.env.BASIC_AUTH_USER}:${process.env.BASIC_AUTH_PASS}`).toString(
          'base64'
        );
    }
    const res = await fetch(url, { headers, method: 'GET' });
    const data = await res.json();

    // 3. Jogosultság ellenőrzés
    const isSuperAdmin =
      Array.isArray(data.roleList) && data.roleList.some((role: any) => role.isSuperAdmin === true);

    if (!isSuperAdmin) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // 4. Path ellenőrzés és revalidate
    const { pathname } = await request.json();
    if (!pathname || typeof pathname !== 'string') {
      return NextResponse.json({ message: 'Pathname is required' }, { status: 400 });
    }

    revalidatePath(pathname);

    return NextResponse.json({ revalidated: true, pathname });
  } catch (err: any) {
    return NextResponse.json(
      { message: 'Error revalidating', error: err?.message },
      { status: 500 }
    );
  }
}
