import { createSelector } from '@reduxjs/toolkit';
import type { RootState } from '@/store/store';

// Profile selectors
export const selectProfile = (state: RootState) => state.profile;
export const selectProfileName = (state: RootState) => state.profile.name;
export const selectProfileEmail = (state: RootState) => state.profile.email;
export const selectProfileRole = (state: RootState) => state.profile.role;
export const selectProfileUserId = (state: RootState) => state.profile.userId;
export const selectProfileUuid = (state: RootState) => state.profile.uuid;
export const selectProfileLoading = (state: RootState) => state.profile.loading;
export const selectProfileError = (state: RootState) => state.profile.error;

// Auth selectors
export const selectAuthUser = (state: RootState) => state.auth.user;
export const selectIsAuthenticated = (state: RootState) => state.auth.isAuthenticated;

// Combined selectors for user data
export const selectUserDisplayName = createSelector(
  [selectProfileName, selectAuthUser],
  (profileName, authUser) => profileName || authUser?.displayName || 'User'
);

export const selectUserEmail = createSelector(
  [selectProfileEmail, selectAuthUser],
  (profileEmail, authUser) => profileEmail || authUser?.email || 'user@example.com'
);

export const selectUserRole = createSelector(
  [selectProfileRole, selectAuthUser],
  (profileRole, authUser) => profileRole || authUser?.role || ''
);

export const selectUserData = createSelector(
  [selectAuthUser, selectProfile],
  (authUser, profile) => ({
    name: profile.name || authUser?.displayName || 'User',
    email: profile.email || authUser?.email || 'user@example.com',
    role: profile.role || authUser?.role || '',
    userId: profile.userId || authUser?.id || null,
    uuid: profile.uuid || authUser?.uuid || '',
  })
);

// Check if profile data is available
export const selectHasProfileData = createSelector(
  [selectUserDisplayName, selectUserEmail],
  (name, email) => !!(name && email && name !== 'User' && email !== 'user@example.com')
);
