"use client";
/**
 * AuthInit 派发器 —— App 启动时恢复登录态
 *
 * 派发时机：仅 mount 时一次（`useEffect` deps = `[dispatch]`，永远不重跑）。
 *
 * 与 <OAuthSessionSync /> 平级：
 *   - AuthStatusChecker: 启动时先跑 storage migration，再恢复登录态、尝试 PSID 直登
 *   - OAuthSessionSync:   持续监听 NextAuth session（"别人在写"）
 */
import { useEffect } from "react";

import { runStorageMigrations } from "@/data/storage/storage_migration";
import { useAuthDispatch } from "./auth-context";
import { Logger } from "@/utils/logger";

const log = new Logger("StoresAuthAuthStatusChecker");

export function AuthStatusChecker() {
  const dispatch = useAuthDispatch();

  useEffect(() => {
    let cancelled = false;

    async function runStartupAuthInit() {
      const migrationResult = await runStorageMigrations();
      if (!migrationResult.success) {
        log.warn(
          { err: migrationResult.error.message },
          "[auth-init] storage migration failed; continuing AuthInit",
        );
      }
      if (cancelled) return;
      log.debug("[auth-init] mount → dispatch AuthInit");
      dispatch({ type: "AuthInit" });
    }

    void runStartupAuthInit();

    return () => {
      cancelled = true;
    };
  }, [dispatch]);

  // 无 UI
  return null;
}
