'use client';

import React, { createContext, useContext, useEffect, useState } from 'react';

interface DevAuthContextType {
  isAuthenticated: boolean;
  user: any;
  login: () => void;
  logout: () => void;
  hasRole: (role: string) => boolean;
}

const DevAuthContext = createContext<DevAuthContextType | null>(null);

export const useDevAuth = () => {
  const context = useContext(DevAuthContext);
  if (!context) {
    throw new Error('useDevAuth must be used within DevAuthProvider');
  }
  return context;
};

interface DevAuthProviderProps {
  children: React.ReactNode;
}

export const DevAuthProvider: React.FC<DevAuthProviderProps> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState(null);

  useEffect(() => {
    // En mode développement, simuler un utilisateur connecté
    if (process.env.NODE_ENV === 'development') {
      setIsAuthenticated(true);
      setUser({
        id: 'dev-user-1',
        username: 'admin',
        email: 'admin@btpxpress.dev',
        firstName: 'Admin',
        lastName: 'BTPXpress',
        roles: ['admin', 'manager', 'user'],
        permissions: ['*']
      });
    }
  }, []);

  const login = () => {
    setIsAuthenticated(true);
    setUser({
      id: 'dev-user-1',
      username: 'admin',
      email: 'admin@btpxpress.dev',
      firstName: 'Admin',
      lastName: 'BTPXpress',
      roles: ['admin', 'manager', 'user'],
      permissions: ['*']
    });
  };

  const logout = () => {
    setIsAuthenticated(false);
    setUser(null);
  };

  const hasRole = (role: string) => {
    return user?.roles?.includes(role) || user?.roles?.includes('admin') || false;
  };

  return (
    <DevAuthContext.Provider value={{
      isAuthenticated,
      user,
      login,
      logout,
      hasRole
    }}>
      {children}
    </DevAuthContext.Provider>
  );
};
