import { fetchCurrentUserProfile } from '../services/userProfileService';
import { getDefaultRoute } from './roleAccess';

export async function persistUserProfileAndGetRoute(): Promise<string> {
  try {
    const profile = await fetchCurrentUserProfile();
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      const parsed = JSON.parse(storedUser);
      localStorage.setItem(
        'user',
        JSON.stringify({
          ...parsed,
          email: profile.email || profile.name || parsed.email,
          full_name: profile.full_name || parsed.full_name,
          role_profile_name: profile.role_profile_name || '',
          custom_site_name: profile.custom_site_name || '',
          custom_phcc_site_name: profile.custom_phcc_site_name || '',
        })
      );
    }
    return getDefaultRoute(profile.role_profile_name);
  } catch (err) {
    console.warn('[AppRouting] Could not load role profile, using default route:', err);
    return '/dashboard';
  }
}

export async function resolveAuthenticatedRoute(): Promise<string | null> {
  const storedUser = localStorage.getItem('user');
  if (!storedUser) {
    return null;
  }

  try {
    const response = await fetch('/api/method/asset_lite.api.custom_api.get_user_details', {
      method: 'GET',
      headers: { Accept: 'application/json' },
      credentials: 'include',
    });

    if (!response.ok) {
      localStorage.removeItem('user');
      return null;
    }

    const data = await response.json();
    if (!data.message?.user_id) {
      localStorage.removeItem('user');
      return null;
    }

    return persistUserProfileAndGetRoute();
  } catch {
    localStorage.removeItem('user');
    return null;
  }
}
