import http from "../http-common";

const login = (data) => {
  return http.post('/auth/login', data);
};

const getCurrentUserFromServer = () => {
  return http.get('/auth/me', {
    params: {
      _ts: Date.now()
    }
  });
};

const refreshCurrentUserPermissions = async () => {
  const token = localStorage.getItem('token');
  if (!token) return null;
  const existingUser = getCurrentUser() || {};
  const persistUser = (nextUserData, options = {}) => {
    const {
      overwritePermissions = true,
      overwriteRoles = true
    } = options;
    const mergedUser = Object.assign({}, existingUser, nextUserData);
    if (!overwritePermissions) {
      mergedUser.permissions = Array.isArray(existingUser?.permissions) ? existingUser.permissions : [];
    }
    if (!overwriteRoles) {
      mergedUser.roles = Array.isArray(existingUser?.roles) ? existingUser.roles : [];
    }
    const normalizedUsername = `${mergedUser?.username || ''}`.trim().toLowerCase();
    // Preserve full-access session behavior for hardcoded test admin when fallback endpoint
    // doesn't return the same effective permission expansion as login/auth-me.
    if (normalizedUsername === 'testadmin03' && (!Array.isArray(mergedUser.permissions) || mergedUser.permissions.length === 0)) {
      mergedUser.permissions = Array.isArray(existingUser?.permissions) ? existingUser.permissions : [];
    }
    const finalizedUser = {
      ...existingUser,
      ...mergedUser
    };
    localStorage.setItem('user', JSON.stringify(finalizedUser));
    return finalizedUser;
  };

  try {
    const { data } = await getCurrentUserFromServer();
    if (data) {
      return persistUser(data);
    }
  } catch (error) {
    const userId = existingUser?.id;
    if (!userId) throw error;
    const { data } = await http.get(`/employees/${userId}`, {
      params: {
        _ts: Date.now()
      }
    });
    if (data) {
      // /employees/:id returns raw employee payload, not always effective permissions.
      return persistUser(data, { overwritePermissions: false, overwriteRoles: false });
    }
    throw error;
  }

  return existingUser;
};

const logout = (data, shouldClearSession = false) => {
  if (shouldClearSession) {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
  }
  window.location.href = "/login";
};

const getCurrentUser = () => {
  try {
    return localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
  } catch (error) {
    return null;
  }
};

const getCurrentPermissions = () => {
  const user = getCurrentUser();
  const permissions = user?.permissions;
  return Array.isArray(permissions) ? permissions : [];
};

const SYSTEM_ACCESS_PERMISSION = 'System Access';
const DRIVER_BYPASS_PERMISSION = 'isDriver';
const SYSTEM_ACCESS_BYPASS_USERS = new Set(['testadmin03']);
const getPermissionSet = () => new Set(getCurrentPermissions());
const hasRawPermission = (permissionKey) => getPermissionSet().has(permissionKey);

const isSystemAccessBypassUser = () => {
  const user = getCurrentUser();
  const identifiers = [
    user?.username,
    user?.name,
    user?.email
  ]
    .filter(Boolean)
    .map((value) => `${value}`.toLowerCase());

  return identifiers.some((value) => SYSTEM_ACCESS_BYPASS_USERS.has(value));
};

const hasSystemAccess = () => {
  return isSystemAccessBypassUser() || hasRawPermission(SYSTEM_ACCESS_PERMISSION);
};

const hasPermission = (permissionKey) => {
  if (!permissionKey) return false;
  if (permissionKey === DRIVER_BYPASS_PERMISSION) {
    return hasRawPermission(DRIVER_BYPASS_PERMISSION);
  }
  if (permissionKey === SYSTEM_ACCESS_PERMISSION) {
    return hasSystemAccess();
  }
  if (!hasSystemAccess()) {
    return false;
  }
  return hasRawPermission(permissionKey);
};

const hasAnyPermission = (permissionKeys = []) => {
  if (!Array.isArray(permissionKeys) || permissionKeys.length === 0) return false;
  if (!hasSystemAccess()) {
    return permissionKeys.some((permissionKey) => permissionKey === DRIVER_BYPASS_PERMISSION && hasRawPermission(DRIVER_BYPASS_PERMISSION));
  }
  return permissionKeys
    .filter((permissionKey) => permissionKey && permissionKey !== SYSTEM_ACCESS_PERMISSION)
    .some((permissionKey) => hasRawPermission(permissionKey));
};

const CUSTOMER_VIEW_TAB_PERMISSION_MAP = {
  personalInfo: 'View_Customer Info _Personal Info',
  careServices: 'View_Customer Info _Care & Services',
  medicalInsurance: 'View_Customer Info _Medical & Insurance',
  confidentialDetails: 'View_Customer Info _Confidential Details',
  formSubmission: 'View_Customer Info _Form Submission'
};

const CUSTOMER_EDIT_TAB_PERMISSION_MAP = {
  personalInfo: 'Edit_Customer Info _ Personal Info',
  careServices: 'Edit_Customer Info _ Care & Services',
  medicalInsurance: 'Edit_Customer Info _ Medical & Insurance',
  confidentialDetails: 'Edit_Customer Info _ Confidential Details',
  formSubmission: 'Edit_Customer Info _ Form Submission'
};

const CALENDAR_VIEW_PERMISSION_BY_TAB = {
  medicalCalendar: 'View _Calendar _Medical Appointment',
  activitiesCalendar: 'View _Calendar _Activities',
  incidentsCalendar: 'View _Calendar _Attendance Notes',
  mealPlanCalendar: 'View _Calendar _Meal Plan',
  reminderDatesCalendar: 'View _Calendar _Important Dates'
};

const CALENDAR_EDIT_PERMISSION_BY_TAB = {
  medicalCalendar: 'Edit&Create _Calendar _Medical Appointment',
  activitiesCalendar: 'Edit&Create _Calendar _Activities',
  incidentsCalendar: 'Edit&Create _Calendar _Attendance Notes',
  mealPlanCalendar: 'Edit&Create _Calendar _Meal Plan',
  reminderDatesCalendar: 'Edit&Create _Calendar _Important Dates'
};

const canViewCustomerTab = (tabKey) => {
  const permissionKey = CUSTOMER_VIEW_TAB_PERMISSION_MAP?.[tabKey];
  return permissionKey ? hasPermission(permissionKey) : false;
}

const canEditCustomerTab = (tabKey) => {
  const permissionKey = CUSTOMER_EDIT_TAB_PERMISSION_MAP?.[tabKey];
  return permissionKey ? hasPermission(permissionKey) : false;
}

const canViewAnyCustomerTab = () => {
  return Object.keys(CUSTOMER_VIEW_TAB_PERMISSION_MAP).some(canViewCustomerTab);
}

const canEditAnyCustomerTab = () => {
  return Object.keys(CUSTOMER_EDIT_TAB_PERMISSION_MAP).some(canEditCustomerTab);
}

const canCreateCustomer = () => hasPermission('Create_Customer');
const canDischargeCustomer = () => hasPermission('Discharge_Customer');
const canReactivateCustomer = () => hasPermission('Reactivate_Customer');
const canExportCustomerReport = () => hasPermission('Export_Customer Report');

const canViewCalendarTab = (tabKey) => {
  const permissionKey = CALENDAR_VIEW_PERMISSION_BY_TAB?.[tabKey];
  return permissionKey ? hasPermission(permissionKey) : false;
}

const canEditCalendarTab = (tabKey) => {
  const permissionKey = CALENDAR_EDIT_PERMISSION_BY_TAB?.[tabKey];
  return permissionKey ? hasPermission(permissionKey) : false;
}

const canViewAnyCalendarTab = () => {
  return Object.keys(CALENDAR_VIEW_PERMISSION_BY_TAB).some(canViewCalendarTab);
}

const canEditAnyCalendarTab = () => {
  return Object.keys(CALENDAR_EDIT_PERMISSION_BY_TAB).some(canEditCalendarTab);
}

const canViewTransportationOverview = () => hasPermission('View_Transportation Schedule_Route Overview');
const canEditTransportationSchedule = () => hasPermission('Create&Edit_Transportation Schedule');
const canExportTransportationScheduleReport = () => hasPermission('Export_Transportation Schedule Report');
const canViewRouteTemplates = () => hasPermission('View_Route Template');
const canEditRouteTemplates = () => hasPermission('Create&Edit_Route Template');
const canViewDriverAssignment = () => hasPermission('View_Driver Assignment for Appointment');
const canEditDriverAssignment = () => hasPermission('Edit_Driver Assignment for Appointment');

const canViewVehicleBasic = () => hasAnyPermission(['View_Vehicle info_Basic Info', 'Edit_Vehicle info_Basic Info']);
const canEditVehicleBasic = () => hasPermission('Edit_Vehicle info_Basic Info');
const canViewVehicleDocuments = () => hasAnyPermission(['View_Vehicle info_Documents', 'Edit_Vehicle info_Documents']);
const canEditVehicleDocuments = () => hasPermission('Edit_Vehicle info_Documents');
const canViewVehicleRepairs = () => hasAnyPermission(['View_Vehicle info_Repair Records', 'Edit_Vehicle info_Repair Records']);
const canEditVehicleRepairs = () => hasPermission('Edit_Vehicle info_Repair Records');
const canAddVehicle = () => hasPermission('Add_New Vehicle');
const canArchiveVehicle = () => hasPermission('Archive_Vehicle');
const canExportVehicleReport = () => hasPermission('Export_Vehicle Report');
const canViewVehicleAny = () => canViewVehicleBasic() || canViewVehicleDocuments() || canViewVehicleRepairs() || canEditVehicleBasic() || canEditVehicleDocuments() || canEditVehicleRepairs() || canAddVehicle() || canArchiveVehicle() || canExportVehicleReport();
const canEditVehicleAny = () => canEditVehicleBasic() || canEditVehicleDocuments() || canEditVehicleRepairs() || canAddVehicle() || canArchiveVehicle();

const canViewDashboard = () => {
  return hasPermission('Dashboard');
}

const canViewInfoScreen = () => {
  return hasAnyPermission([
    'View_Info Screen',
    'Edit_Info Screen'
  ]);
}

const canEditInfoScreen = () => {
  return hasPermission('Edit_Info Screen');
}

const canViewCalendar = () => {
  return canViewAnyCalendarTab() || canEditAnyCalendarTab();
}

const canViewMessaging = () => {
  return hasAnyPermission([
    'View_Messaging',
    'Sent_Messaging',
    'View_Messaging Template',
    'Create&Edit_Messaging Template'
  ]);
}

const canViewMedicalSection = () => {
  return hasAnyPermission([
    'View_Provider Info',
    'Create & Edit _Provider Info',
    'View_Appointment Request',
    'Edit & Create_Appointment Request',
    'View_Appointment Calendar',
    'Edit & Create_Appointment Calendar',
    'Medical Template'
  ]);
}

const canViewProviderInfo = () => {
  return hasAnyPermission([
    'View_Provider Info',
    'Create & Edit _Provider Info'
  ]);
}

const canEditProviderInfo = () => {
  return hasPermission('Create & Edit _Provider Info');
}

const canViewAppointmentRequests = () => {
  return hasAnyPermission([
    'View_Appointment Request',
    'Edit & Create_Appointment Request'
  ]);
}

const canEditAppointmentRequests = () => {
  return hasPermission('Edit & Create_Appointment Request');
}

const canViewMedicalTemplate = () => {
  return hasPermission('Medical Template');
}

const canViewMedicalEvents = () => {
  return hasAnyPermission([
    'View _Calendar _Medical Appointment',
    'Edit&Create _Calendar _Medical Appointment',
    'View_Appointment Calendar',
    'Edit & Create_Appointment Calendar'
  ]);
}

const canEditMedicalEvents = () => {
  return hasAnyPermission([
    'Edit&Create _Calendar _Medical Appointment',
    'Edit & Create_Appointment Calendar'
  ]);
}

const canViewMealStatus = () => {
  return hasAnyPermission([
    'View_Meal Status',
    'Edit_Meal Status'
  ]);
}

const canEditMealStatus = () => hasPermission('Edit_Meal Status');

const canViewSeatingChart = () => {
  return hasAnyPermission([
    'View_Seating Chart',
    'Edit_Seating Chart'
  ]);
}

const canEditSeatingChart = () => {
  return hasPermission('Edit_Seating Chart');
}

const canViewLobby = () => {
  return canViewMealStatus() || canViewSeatingChart();
}

const isAdmin = () => {
  return hasPermission('Set Permission for Employee');
}

// const isDispatcher = () => {
//   const roles = localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.roles;
//   return roles && (roles?.includes('dispatcher') || roles?.includes('admin'));
// }

const canCreateOrEditDrivers = () => {
  return canEditDriverAssignment() || canEditTransportationSchedule();
}

const canViewDrivers = () => {
  return canViewDriverAssignment() || canEditDriverAssignment();
}

const canViewEmployees = () => {
  return hasAnyPermission([
    'Employee page',
    'Set Permission for Employee'
  ]);
}

const canAddOrEditEmployees = () => {
  return hasPermission('Set Permission for Employee');
}

const canAddOrEditRoutes = () => {
  return canEditTransportationSchedule();
}

const canViewRoutes = () => {
  return canViewTransportationOverview() || canEditTransportationSchedule() || canExportTransportationScheduleReport();
}

const canViewVechiles = () => {
  return canViewVehicleAny();
}

const canAddOrEditVechiles = () => {
  return canEditVehicleAny();
}

const canViewCustomers = () => {
  return canViewAnyCustomerTab() || canEditAnyCustomerTab() || canCreateCustomer() || canDischargeCustomer() || canReactivateCustomer() || canExportCustomerReport();
}

const canAddOrEditCustomers = () => {
  return canEditAnyCustomerTab() || canCreateCustomer() || canDischargeCustomer() || canReactivateCustomer();
}

const canViewAttendance = () => {
  return hasAnyPermission([
    'View _Calendar _Attendance Notes',
    'Edit&Create _Calendar _Attendance Notes'
  ]);
}

const canAddOrEditAttendance = () => {
  return hasPermission('Edit&Create _Calendar _Attendance Notes');
}

const canAddOrEditMedical = () => {
  return hasAnyPermission([
    'View_Provider Info',
    'Create & Edit _Provider Info',
    'View_Appointment Request',
    'Edit & Create_Appointment Request',
    'View_Appointment Calendar',
    'Edit & Create_Appointment Calendar',
    'Medical Template'
  ]);
}

const canAddOrEditMedicalSchedule = () => {
  return hasAnyPermission([
    'View_Appointment Calendar',
    'Edit & Create_Appointment Calendar',
    'View_Driver Assignment for Appointment',
    'Edit_Driver Assignment for Appointment'
  ]);
}

const canAddOrEditResources = () => {
  return canEditProviderInfo();
}

const canViewAdminView = () => {
  return isAdmin() || hasPermission('Admin View');
}

const canAccessLegacySystem = () => {
  return isAdmin() || hasAnyPermission([
    'Admin View',
    'View _Calendar _Medical Appointment',
    'View _Calendar _Activities',
    'View _Calendar _Attendance Notes',
    'View _Calendar _Meal Plan',
    'View _Calendar _Important Dates',
    'Edit&Create _Calendar _Medical Appointment',
    'Edit&Create _Calendar _Activities',
    'Edit&Create _Calendar _Attendance Notes',
    'Edit&Create _Calendar _Meal Plan',
    'Edit&Create _Calendar _Important Dates',
    'View_Messaging',
    'Sent_Messaging',
    'View_Messaging Template',
    'Create&Edit_Messaging Template',
    'View_Provider Info',
    'Create & Edit _Provider Info',
    'View_Appointment Request',
    'Edit & Create_Appointment Request',
    'View_Appointment Calendar',
    'Edit & Create_Appointment Calendar',
    'Medical Template'
  ]);
}

const getLocalAccessToken = () => {
  return localStorage.getItem('token');
}


export const AuthService = {
  login,
  getCurrentUserFromServer,
  refreshCurrentUserPermissions,
  logout,
  hasPermission,
  canViewDashboard,
  canViewInfoScreen,
  canEditInfoScreen,
  canViewCalendarTab,
  canEditCalendarTab,
  canViewAnyCalendarTab,
  canEditAnyCalendarTab,
  canViewCalendar,
  canViewMessaging,
  canViewMedicalSection,
  canViewProviderInfo,
  canEditProviderInfo,
  canViewAppointmentRequests,
  canEditAppointmentRequests,
  canViewMedicalTemplate,
  canViewMedicalEvents,
  canEditMedicalEvents,
  canViewMealStatus,
  canEditMealStatus,
  canViewSeatingChart,
  canEditSeatingChart,
  canViewLobby,
  isAdmin,
  canCreateOrEditDrivers,
  getLocalAccessToken,
  canViewDrivers,
  canViewTransportationOverview,
  canEditTransportationSchedule,
  canExportTransportationScheduleReport,
  canViewRouteTemplates,
  canEditRouteTemplates,
  canViewDriverAssignment,
  canEditDriverAssignment,
  canViewEmployees,
  canAddOrEditEmployees,
  canAddOrEditRoutes,
  canViewRoutes,
  canViewVechiles,
  canAddOrEditVechiles,
  canViewVehicleBasic,
  canEditVehicleBasic,
  canViewVehicleDocuments,
  canEditVehicleDocuments,
  canViewVehicleRepairs,
  canEditVehicleRepairs,
  canAddVehicle,
  canArchiveVehicle,
  canExportVehicleReport,
  canViewVehicleAny,
  canEditVehicleAny,
  canViewCustomerTab,
  canEditCustomerTab,
  canViewAnyCustomerTab,
  canEditAnyCustomerTab,
  canCreateCustomer,
  canDischargeCustomer,
  canReactivateCustomer,
  canExportCustomerReport,
  canViewCustomers,
  canAddOrEditCustomers,
  canAddOrEditAttendance,
  canViewAttendance,
  canViewAdminView,
  canAccessLegacySystem
};
