'use client'

import { useEffect } from 'react'
import { signOut } from 'next-auth/react'
import { setSessionActive } from '@/lib/session-monitor'

/**
 * Watches every client-side fetch and ends the session as soon as an API call
 * comes back 401 or 403.
 */

const LOGIN_URL = '/auth/login'
const UNAUTHORIZED_STATUSES = [401, 403]
// NextAuth's own endpoints legitimately answer 401 while signing in/out.
const IGNORED_PREFIXES = ['/api/auth/']

let fetchPatched = false
let expiring = false

const shouldWatch = (url: string) => {
  try {
    const parsed = new URL(url, window.location.origin)
    if (parsed.origin !== window.location.origin) return false
    if (!parsed.pathname.startsWith('/api/')) return false
    return !IGNORED_PREFIXES.some((prefix) => parsed.pathname.startsWith(prefix))
  } catch {
    return false
  }
}

const resolveUrl = (input: RequestInfo | URL) => {
  if (typeof input === 'string') return input
  if (input instanceof URL) return input.toString()
  return input.url
}

export const expireSession = async () => {
  if (expiring) return
  expiring = true

  console.log('🔐 Session expired (401/403) - signing out')

  try {
    setSessionActive(false)
  } catch {
    // session-monitor is best-effort; never block the sign-out on it
  }

  try {
    await signOut({ callbackUrl: `${LOGIN_URL}?expired=1`, redirect: true })
  } catch {
    window.location.replace(`${LOGIN_URL}?expired=1`)
  }
}

export default function SessionExpiryProvider({
  children,
}: {
  children: React.ReactNode
}) {
  useEffect(() => {
    if (fetchPatched) return
    fetchPatched = true

    const originalFetch = window.fetch.bind(window)

    window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
      const response = await originalFetch(input, init)

      if (
        UNAUTHORIZED_STATUSES.includes(response.status) &&
        !window.location.pathname.startsWith(LOGIN_URL) &&
        shouldWatch(resolveUrl(input))
      ) {
        void expireSession()
      }

      return response
    }
  }, [])

  return <>{children}</>
}
