package ru.micord.ervu.account_applications.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.micord.ervu.account_applications.security.service.EncryptionService;
import ru.micord.ervu.account_applications.service.UserApplicationListService;
import ru.micord.ervu.account_applications.websocket.dto.ProcessErrorMsg;
import ru.micord.ervu.account_applications.websocket.dto.ProcessResponseDto;

/**
 * @author gulnaz
 */
@RestController
public class UserApplicationController {
  private static final Logger LOGGER = LoggerFactory.getLogger(UserApplicationController.class);

  private final UserApplicationListService applicationService;
  private final EncryptionService encryptionService;

  public UserApplicationController(UserApplicationListService applicationService,
                                   EncryptionService encryptionService) {
    this.applicationService = applicationService;
    this.encryptionService = encryptionService;
  }

  @PutMapping(value = "/status", consumes = MediaType.APPLICATION_JSON_VALUE)
  public Long updateStatus(@RequestBody ProcessResponseDto data) {
    Long appNumber = data.body().applicationNumber();

    switch (data.className()) {
      case UPDATE -> {
        LOGGER.info("update by appNumber = {}", appNumber);
        String tempPass = data.body().tempPass();

        if (StringUtils.hasText(tempPass)) {
          String encryptedPassword = encryptionService.encrypt(tempPass);
          applicationService.savePassword(appNumber, encryptedPassword);
        }
        else {
          applicationService.saveAcceptedStatus(appNumber);
        }
      }
      case PROCESS_ERROR -> {
        ProcessErrorMsg errorMsg = data.body().msg();
        String msg = errorMsg == null ? "unknown error" : errorMsg.message();
        LOGGER.error("error by appNumber = {}, message: {}", appNumber, msg);
        applicationService.saveError(appNumber, msg);
      }
    }

    return appNumber;
  }
}
