package com.oguerreiro.resilient.security.custom;

import java.io.Serializable;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;

public class CustomPermissionEvaluator implements PermissionEvaluator {

  // This method is used to check permissions on a domain object (e.g., User or Resource)
  @Override
  public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
    // Retrieve the current class instance from ThreadLocal
    Object currentInstance = ResilientSecurityContextAspect.getCurrentTargetInstance();

    if (authentication == null) {
      return false;  // If no authentication context exists, deny permission
    }

    String username = authentication.getName();  // Retrieve the current username
    String requiredPermission = (String) permission;  // Retrieve the required permission (e.g., 'READ', 'WRITE')

    // Custom logic for permission evaluation, e.g., checking if the user has the required permission
    if ("READ".equals(requiredPermission)) {
      return hasReadPermission(username);  // Custom logic for 'READ' permission
    } else if ("WRITE".equals(requiredPermission)) {
      return hasWritePermission(username);  // Custom logic for 'WRITE' permission
    }

    return true;
  }

  // This method is used to check permissions on an object based on its ID and type
  @Override
  public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
      Object permission) {
    // Retrieve the current class instance from ThreadLocal
    Object currentInstance = ResilientSecurityContextAspect.getCurrentTargetInstance();

    if (authentication == null) {
      return false;  // If no authentication context exists, deny permission
    }

    // If permission is based on a specific target (e.g., a specific resource or entity), you can implement logic here
    String username = authentication.getName();
    return hasReadPermission(username);  // For example, checking if the user has read permission
  }

  // Custom logic for checking "READ" permission
  private boolean hasReadPermission(String username) {
    // For example, check if the username starts with "admin" to allow "READ" permission
    return username.startsWith("admin");
  }

  // Custom logic for checking "WRITE" permission
  private boolean hasWritePermission(String username) {
    // For example, check if the username starts with "admin" to allow "WRITE" permission
    return username.startsWith("admin");
  }
}
