import { Navigate, Outlet } from 'react-router'
import type { WorkspaceType } from '../../domain/enums'
import { useSessionStore } from '../../stores/sessionStore'
import { SessionStatus } from '../../stores/sessionStore'
import { canAccessWorkspace } from '../../lib/permissions'
import { AccessDenied } from './AccessDenied'
import { SessionExpired } from './SessionExpired'

interface ProtectedRouteProps {
  workspace?: WorkspaceType
}

export function ProtectedRoute({ workspace }: ProtectedRouteProps) {
  const { isAuthenticated, currentUser, sessionStatus } = useSessionStore()

  if (!isAuthenticated || sessionStatus === SessionStatus.UNAUTHENTICATED) {
    return <Navigate to="/auth/login" replace />
  }

  if (sessionStatus === SessionStatus.EXPIRED) {
    return <SessionExpired />
  }

  if (workspace && currentUser && !canAccessWorkspace(currentUser, workspace)) {
    const workspaceLabel: Record<string, string> = {
      SUPPLY: 'Supply',
      DEMAND: 'Demand',
    }
    return (
      <AccessDenied
        message={`Sie haben keine Berechtigung für den ${workspaceLabel[workspace] ?? workspace}-Bereich.`}
      />
    )
  }

  return <Outlet />
}
