/**
 * Sandbox Context
 * Provides sandbox mode state and toggle functionality throughout the app
 */

import React, { createContext, useContext, useEffect, ReactNode } from 'react';
import { useSandboxStatus, useToggleSandbox } from '../hooks/useSandbox';
import { useEntitlements } from '../hooks/useEntitlements';

interface SandboxContextType {
  /** Whether the app is currently in sandbox/test mode */
  isSandbox: boolean;
  /** Whether sandbox mode is available for this business */
  sandboxEnabled: boolean;
  /** Whether the sandbox status is loading */
  isLoading: boolean;
  /** Toggle between live and sandbox mode */
  toggleSandbox: (enableSandbox: boolean) => Promise<void>;
  /** Whether a toggle operation is in progress */
  isToggling: boolean;
}

const SandboxContext = createContext<SandboxContextType | undefined>(undefined);

interface SandboxProviderProps {
  children: ReactNode;
}

export const SandboxProvider: React.FC<SandboxProviderProps> = ({ children }) => {
  const { data: status, isLoading } = useSandboxStatus();
  const toggleMutation = useToggleSandbox();
  const { hasFeature } = useEntitlements();

  // Check if tenant has API access - sandbox toggle requires API access
  const hasApiAccess = hasFeature('api_access');

  const toggleSandbox = async (enableSandbox: boolean) => {
    await toggleMutation.mutateAsync(enableSandbox);
  };

  // Store sandbox mode in localStorage for persistence across tabs
  useEffect(() => {
    if (status?.sandbox_mode !== undefined) {
      localStorage.setItem('sandbox_mode', String(status.sandbox_mode));
    }
  }, [status?.sandbox_mode]);

  const value: SandboxContextType = {
    isSandbox: status?.sandbox_mode ?? false,
    // Only show sandbox toggle if both: sandbox is enabled for business AND tenant has API access
    sandboxEnabled: (status?.sandbox_enabled ?? false) && hasApiAccess,
    isLoading,
    toggleSandbox,
    isToggling: toggleMutation.isPending,
  };

  return (
    <SandboxContext.Provider value={value}>
      {children}
    </SandboxContext.Provider>
  );
};

export const useSandbox = (): SandboxContextType => {
  const context = useContext(SandboxContext);
  if (context === undefined) {
    // Return default values when used outside SandboxProvider
    // This happens for platform admins who don't have sandbox mode
    return {
      isSandbox: false,
      sandboxEnabled: false,
      isLoading: false,
      toggleSandbox: async () => {},
      isToggling: false,
    };
  }
  return context;
};

export default SandboxContext;
