import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { AuthService } from "../modules/auth/services/services-auth";
import type { User } from "src/modules/shared/models/user.models";

export type CompanyRole = 'guest' | 'supervisor' | 'accounting' | 'human_resources' | 'employee';

const TestUsers: Record<CompanyRole, User> = {
  guest: { firstName: 'Unknown', lastName: 'Unknown', email: 'guest@guest.com', role: 'guest' },
  supervisor: { firstName: 'User', lastName: 'Test', email: 'user@targointernet.com', role: 'supervisor' },
  accounting: { firstName: 'Robin', lastName: 'Clark', email: 'user5@example.test', role: 'supervisor' },
  human_resources: { firstName: 'Robin', lastName: 'Clark', email: 'user5@example.test', role: 'supervisor' },
  employee: { firstName: 'Robin', lastName: 'Clark', email: 'user5@example.test', role: 'supervisor' },
}

export const useAuthStore = defineStore('auth', () => {  
  const user = ref<User>(TestUsers.guest);
  const authError = ref("");
  const isAuthorizedUser = computed(() => user.value.role !== 'guest');

  const login = () => {
    //TODO: manage customer login process
  };

  const oidcLogin = () => {
    const oidcPopup = AuthService.oidcLogin();
    if (!oidcPopup) { 
      authError.value = "You have popups blocked on this website!";
    }
  };

  const logout = () => {
    user.value = TestUsers.guest;
  };

  const setUser = (bypassRole: string) => {
    if (bypassRole in TestUsers) { 
      user.value = TestUsers[bypassRole as CompanyRole];
    }
    else { 
      user.value = TestUsers.guest; 
    }
  };

  return { user, authError, isAuthorizedUser, login, oidcLogin, logout, setUser };
});

