// src/features/client-portal-auth/use-client-auth-guard.ts
"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { useLocale } from "next-intl"

import { customerPortalTokenStorage } from "@/src/lib/api/customer-portal-storage"
import { getCustomerPortalMe } from "@/src/lib/api/customer-portal"
import { getJwtClaim } from "@/src/lib/api/jwt-utils"

type Mode = "redirectIfAuth" | "requireAuth"

export function useClientAuthGuard(opts: { mode: Mode; redirectTo: string }) {
  const router = useRouter()
  const locale = useLocale()
  const [checking, setChecking] = useState(true)

  useEffect(() => {
    let alive = true

    ;(async () => {
      try {
        const access = customerPortalTokenStorage.getAccess()
        if (!access) {
          if (opts.mode === "requireAuth") {
            router.replace(`/${locale}/client/login?reason=expired`)
          }
          return
        }

        // Vérifie le token côté API
        await getCustomerPortalMe()

        // Vérifie si l'utilisateur doit changer son mot de passe
        // (claim injecté dans le JWT à la création du compte portail)
        const mustChange = getJwtClaim<boolean>(access, "must_change_password")
        if (mustChange === true) {
          // Redirige vers le changement de mdp quelle que soit le mode
          const changePwdPath = `/${locale}/client/change-password`
          if (typeof window !== "undefined" && !window.location.pathname.includes("/change-password")) {
            router.replace(changePwdPath)
            return
          }
        }

        if (opts.mode === "redirectIfAuth") {
          router.replace(opts.redirectTo)
        }
      } catch {
        customerPortalTokenStorage.clear()
        if (opts.mode === "requireAuth") {
          router.replace(`/${locale}/client/login?reason=expired`)
        }
      } finally {
        if (alive) setChecking(false)
      }
    })()

    return () => {
      alive = false
    }
  }, [opts.mode, opts.redirectTo, router, locale])

  return { checking }
}
