import { Navigate } from 'react-router-dom';
import useAuthStore from '../store/useAuthStore';
import { getCompanySlug } from './slug';

export function RequireAuth({ children }) {
  const token = useAuthStore((s) => s.token);
  if (!token) return <Navigate to="/login" replace />;
  return children;
}

export function RequireSuperAdmin({ children }) {
  const user = useAuthStore((s) => s.user);
  if (!user) return <Navigate to="/login" replace />;
  if (user.role !== 'super_admin') {
    const slug = getCompanySlug(user.company_name);
    return <Navigate to={`/${slug}/pos`} replace />;
  }
  return children;
}

export function RequireOwner({ children }) {
  const user = useAuthStore((s) => s.user);
  if (!user) return <Navigate to="/login" replace />;
  if (user.role !== 'owner') {
    const slug = getCompanySlug(user.company_name);
    return <Navigate to={`/${slug}/pos`} replace />;
  }
  return children;
}

export function GuestOnly({ children }) {
  const token = useAuthStore((s) => s.token);
  const user = useAuthStore((s) => s.user);
  if (token && user) {
    if (user.role === 'super_admin') return <Navigate to="/admin/companies" replace />;
    const slug = getCompanySlug(user.company_name);
    if (user.role === 'owner') return <Navigate to={`/${slug}/dashboard`} replace />;
    return <Navigate to={`/${slug}/pos`} replace />;
  }
  return children;
}
