'use client';

import { env } from './env';
import { useAuthStore } from '@/stores/auth-store';

/**
 * 鉴权诊断信标(共享)—— bootstrap 首屏路径 + api-client 运行期掉线路径共用。
 * 同时打 console(本地/开 devtools 可见)+ 打服务端日志(远端对接方复现时 grep pac-service
 * 即可,不用他们开 devtools)。失败事件里的 embedded/storageWritable/storedRefresh 是服务端
 * 判「真掉线 vs 存储被 iframe 分区」+ 触发企微告警的依据。纯诊断,失败静默,绝不影响鉴权主流程。
 */

/** 当前 store 的 token 快照(反水合后)—— 诊断嵌入重载/掉线时"token 到底还在不在" */
export function authStoreSnap() {
  const s = useAuthStore.getState();
  return {
    storedAccess: Boolean(s.accessToken),
    storedRefresh: Boolean(s.refreshToken),
    storedAccessValid: Boolean(s.accessToken && s.expiresAt && Date.now() < s.expiresAt),
  };
}

/** 环境/存储探针 —— storageWritable(存储能不能用)+ isEmbedded(是否 iframe)+ 宿主/重载/UA。 */
export function authEnvSnap() {
  let storageWritable = false;
  try {
    const k = '__pac_probe__';
    localStorage.setItem(k, '1');
    storageWritable = localStorage.getItem(k) === '1';
    localStorage.removeItem(k);
  } catch {
    storageWritable = false; // 抛错 = 存储被禁/分区(隐私模式 / 第三方 iframe 被拦)
  }
  let isEmbedded = false;
  try {
    isEmbedded = window.self !== window.top;
  } catch {
    isEmbedded = true; // 跨源访问 window.top 抛错 = 确实被跨源嵌入
  }
  let hostOrigin: string | null = null;
  try {
    const anc = window.location.ancestorOrigins;
    hostOrigin =
      (anc && anc.length ? anc[0] : null) ??
      (document.referrer ? new URL(document.referrer).origin : null);
  } catch {
    hostOrigin = null;
  }
  let isReload = false;
  try {
    const nav = performance.getEntriesByType('navigation')[0] as
      | PerformanceNavigationTiming
      | undefined;
    isReload = nav?.type === 'reload';
  } catch {
    /* noop */
  }
  const ua = typeof navigator !== 'undefined' ? navigator.userAgent.slice(0, 160) : '';
  return { storageWritable, isEmbedded, hostOrigin, isReload, ua };
}

export interface AuthDiagPayload {
  ev: string;
  hadCode?: boolean;
  codeTag?: string | null;
  storedAccess?: boolean;
  storedRefresh?: boolean;
  storedAccessValid?: boolean;
  err?: string | null;
  storageWritable?: boolean;
  isEmbedded?: boolean;
  hostOrigin?: string | null;
  isReload?: boolean;
  ua?: string;
}

export function reportAuthDiag(payload: AuthDiagPayload) {
  try {
    // eslint-disable-next-line no-console
    console.info('[auth-diag]', payload);
  } catch {
    /* noop */
  }
  try {
    const url = new URL('/pac/v1/auth/client-diag', env.apiBaseUrl).toString();
    const body = JSON.stringify({ phase: 'bootstrap', ...payload });
    // 用 fetch(不用 sendBeacon):sendBeacon 强制带凭据,遇服务端 CORS 通配 origin 会被拦。
    // keepalive 保证即使随后页面跳转/卸载,这条诊断也能发出。
    void fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body,
      keepalive: true,
      credentials: 'omit',
    }).catch(() => {
      /* 诊断失败静默 */
    });
  } catch {
    /* noop */
  }
}
