package net.whydah.crmservice.customer;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import net.whydah.crmservice.security.Authentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ratpack.exec.Blocking;
import ratpack.handling.Context;
import ratpack.handling.Handler;

import static ratpack.jackson.Jackson.json;

@Singleton
public class GetCustomerHandler implements Handler {

    private static final Logger log = LoggerFactory.getLogger(GetCustomerHandler.class);

    private final CustomerRepository customerRepository;

    @Inject
    public GetCustomerHandler(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }
    @Override
    public void handle(Context ctx) throws Exception {

        String customerRef = ctx.getPathTokens().get("customerRef");
        
        if (Authentication.isAdminUser()) {
        	
        } else if (customerRef == null || !customerRef.equals(Authentication.getAuthenticatedUser().getPersonRef())) {
            log.debug("User {} with personRef {} not authorized to get data for personRef {}", Authentication.getAuthenticatedUser().getUid(), Authentication.getAuthenticatedUser().getPersonRef(), customerRef);
            ctx.clientError(401);
            return;
        }

        log.trace("Getting customer with ref={}", customerRef);

        Blocking.get(() -> customerRepository.getCustomer(customerRef)).then(customer -> {
            log.trace("Found customer-data: {}", customer);
            if (customer != null) {
                ctx.render(json(customer));
            } else {
                ctx.clientError(404); //Not found
            }
        });
    }
}

@@ -420,17 +420,16 @@
 ndler %7B%0A
-%0A
     priv
@@ -707,24 +707,25 @@
 tory;%0A    %7D%0A
+%0A
     @Overrid
@@ -781,17 +781,16 @@
 ption %7B%0A
-%0A
         
@@ -907,17 +907,8 @@
 ) %7B%0A
-        %09
 %0A   
@@ -1115,16 +1115,31 @@
 onRef %7B%7D
+. Returning 401
 %22, Authe
@@ -1355,17 +1355,25 @@
 er with 
-r
+customerR
 ef=%7B%7D%22, 
@@ -1639,16 +1639,124 @@
  else %7B%0A
+                log.debug(%22Did not find any customer data for customerRef=%7B%7D. Returning 404%22, customerRef);%0A
         

add debug logging to customer data not found in GetCustomerHandler.