export type BootstrapFrappeUserResult = { ok: true } | { ok: false };

/**
 * If a Frappe session cookie exists but ASM localStorage is empty, populate a minimal `user`
 * object so the SPA can render. Mirrors the get_logged_user + User fetch pattern in Header.tsx.
 */
export async function bootstrapFrappeUserFromSession(): Promise<BootstrapFrappeUserResult> {
  try {
    const userResponse = await fetch('/api/method/frappe.auth.get_logged_user', {
      method: 'GET',
      headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
      credentials: 'include',
    });

    if (!userResponse.ok) {
      return { ok: false };
    }

    const userData: { message?: string } = await userResponse.json();
    const username = userData?.message;

    if (!username || username === 'Guest') {
      return { ok: false };
    }

    let full_name = username;
    let user_image = '';

    try {
      const fullNameResponse = await fetch(
        `/api/resource/User/${encodeURIComponent(username)}?fields=["full_name","user_image"]`,
        {
          method: 'GET',
          headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
          credentials: 'include',
        }
      );
      if (fullNameResponse.ok) {
        const fullNameData: { data?: { full_name?: string; user_image?: string } } =
          await fullNameResponse.json();
        if (fullNameData.data?.full_name) {
          full_name = fullNameData.data.full_name;
        }
        if (fullNameData.data?.user_image) {
          user_image = fullNameData.data.user_image;
        }
      }
    } catch {
      // keep defaults from username
    }

    const obj = {
      email: username,
      full_name,
      user_image,
      roles: [] as string[],
    };
    localStorage.setItem('user', JSON.stringify(obj));
    return { ok: true };
  } catch {
    return { ok: false };
  }
}
