import { javaPost } from './apiClient';

/* eslint-disable @typescript-eslint/no-explicit-any */
export async function isUserSuperAdmin(): Promise<boolean> {
  try {
    const res = await fetch('/api/user-access', { credentials: 'include' });
    if (!res.ok) return false;
    const data = await res.json();
    return (
      Array.isArray(data.roleList) && data.roleList.some((role: any) => role.isSuperAdmin === true)
    );
  } catch {
    return false;
  }
}

function buildServerHeaders(cookie: string | null): Record<string, string> {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  };

  if (cookie) {
    headers.Cookie = cookie;
  }

  const isTest = process.env.NEXT_PUBLIC_ENV === 'test';
  if (isTest) {
    const username = process.env.BASIC_AUTH_USER || '';
    const password = process.env.BASIC_AUTH_PASS || '';
    if (username && password) {
      const encoded = Buffer.from(`${username}:${password}`).toString('base64');
      headers.Authorization = `Basic ${encoded}`;
    }
  }

  return headers;
}

export async function verifySuperAdminServerSide(cookie: string | null): Promise<boolean> {
  try {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
    const url = apiUrl.replace(/\/$/, '') + '/accessManagement/getAccessConfig';

    const res = await fetch(url, {
      headers: buildServerHeaders(cookie),
      method: 'GET',
      cache: 'no-store',
    });
    if (!res.ok) return false;
    const data = await res.json();
    return (
      Array.isArray(data.roleList) && data.roleList.some((role: any) => role.isSuperAdmin === true)
    );
  } catch {
    return false;
  }
}

export async function isLoggedIn(cookie: string | null): Promise<boolean> {
  try {
    const res = await javaPost(
      'userLogin/isLoggedIn',
      {},
      {
        headers: buildServerHeaders(cookie),
        cache: 'no-store',
        next: {
          revalidate: 0,
        },
      }
    );

    if (typeof res === 'boolean') return res;
    if (typeof res === 'string') return res.toLowerCase() === 'true';
    if (res && typeof res === 'object' && 'loggedIn' in res) {
      return Boolean((res as any).loggedIn);
    }

    return Boolean(res);
  } catch {
    return false;
  }
}
