package com.braintreeocc.controllers;

import com.braintree.facade.BrainTreeUserFacade;
import com.braintree.form.UpdateCreditCardBillingAddressForm;
import com.braintree.hybris.data.ws.UpdateCreditCardBillingAddressRequest;
import de.hybris.platform.commercefacades.user.data.AddressData;
import de.hybris.platform.commercewebservicescommons.dto.user.AddressWsDTO;
import de.hybris.platform.webservicescommons.swagger.ApiBaseSiteIdAndUserIdParam;
import io.swagger.v3.oas.annotations.Operation;
import javax.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/{baseSiteId}")
public class BraintreeCreditCardPaymentMethodController extends BraintreeBaseCommerceController {

    private static final String ADDRESS_MAPPING = "firstName,lastName,titleCode,email,phone,cellphone,line1,line2,town,postalCode,region(isocode),district,country(isocode),defaultAddress";
    private static final String OBJECT_NAME_ADDRESS = "address";

    @Resource(name = "userFacade")
    private BrainTreeUserFacade userFacade;


    @Secured({"ROLE_CUSTOMERGROUP", "ROLE_TRUSTED_CLIENT", "ROLE_CUSTOMERMANAGERGROUP"})
    @PutMapping(value = "/braintree/updateCreditCardBillingAddress")
    @ResponseStatus(HttpStatus.OK)
    @Operation(operationId = "updateBillingAddress", summary = "Update billing address for credit card payment method", description = "Update billing address for credit card payment method")
    @ApiBaseSiteIdAndUserIdParam
    public void updateCreditCardBillingAddress(
        @RequestBody final UpdateCreditCardBillingAddressRequest updateCreditCardBillingAddressRequest) {
        final AddressWsDTO address = updateCreditCardBillingAddressRequest.getBillingAddress();
        validate(address, OBJECT_NAME_ADDRESS, getAddressDTOValidator());
        final AddressData addressData = getDataMapper().map(address, AddressData.class, ADDRESS_MAPPING);
        UpdateCreditCardBillingAddressForm form = new UpdateCreditCardBillingAddressForm(addressData,
            updateCreditCardBillingAddressRequest.getPaymentMethodId());
        userFacade.editPaymentMethod(form);

    }

}
