import { createContext, useState } from 'react';
import type { ReactNode } from 'react';
import type { User } from '../types/auth';
import { setApiClientUserId } from '../services/apiClient';

interface AuthContextValue {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  setRole: (role: 'ADMIN' | 'MANAGER' | 'USER') => void;
}

export const AuthContext = createContext<AuthContextValue | null>(null);

interface AuthProviderProps {
  children: ReactNode;
}

const ROLE_USERS: Record<string, User> = {
  ADMIN: { userId: 1, loginId: 'admin', userName: '관리자', role: 'ADMIN' },
  MANAGER: { userId: 7, loginId: 'manager', userName: '매니저', role: 'MANAGER' },
  USER: { userId: 2, loginId: 'user', userName: '사용자', role: 'USER' },
};

const getInitialUser = (): User => {
  const savedRole = localStorage.getItem('snp-role') as 'ADMIN' | 'MANAGER' | 'USER' | null;
  const u = ROLE_USERS[savedRole || 'ADMIN'];
  setApiClientUserId(u.userId);
  return u;
};

const AuthProvider = ({ children }: AuthProviderProps) => {
  const [user, setUser] = useState<User>(getInitialUser);

  const setRole = (role: 'ADMIN' | 'MANAGER' | 'USER') => {
    localStorage.setItem('snp-role', role);
    const u = ROLE_USERS[role];
    setUser(u);
    setApiClientUserId(u.userId);
    window.location.reload();
  };

  return (
    <AuthContext.Provider value={{ user, isAuthenticated: true, isLoading: false, setRole }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;
