package ru.micord.ervu.account_applications.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;
import ru.micord.ervu.account_applications.component.dao.AuditDao;
import ru.micord.ervu.account_applications.dao.UserApplicationListDao;
import ru.micord.ervu.account_applications.security.context.SecurityContext;
import ru.micord.ervu.account_applications.security.model.UserSession;
import utils.DateTimeUtil;

import static ru.micord.ervu.account_applications.enums.ApplicationStatus.ACCEPTED;
import static ru.micord.ervu.account_applications.enums.ApplicationStatus.AGREED;

/**
 * @author gulnaz
 */
@Service
public class UserApplicationListService {

  private final UserApplicationListDao dao;
  private final AuditDao auditDao;
  private final SecurityContext securityContext;

  public UserApplicationListService(UserApplicationListDao dao, AuditDao auditDao, SecurityContext securityContext) {
    this.dao = dao;
    this.auditDao = auditDao;
    this.securityContext = securityContext;
  }

  public void savePassword(Long appNumber, String encodedPass) {
    dao.savePassword(appNumber, encodedPass);
    saveAuditStatusByAppNumber(appNumber, ACCEPTED.name());
  }

  public boolean userExists(String login){
    return dao.userExists(login);
  }

  public void saveAcceptedStatus(long appNumber) {
    dao.saveAcceptedStatus(appNumber);
    saveAuditStatusByAppNumber(appNumber, ACCEPTED.name());
  }

  public void saveError(long appNumber, String errorMsg) {
    dao.saveError(appNumber, errorMsg);
    saveAuditStatusByAppNumber(appNumber, AGREED.name());
  }

  private void saveAuditStatusByAppNumber(long appNumber, String status) {
    List<Long> appIds = auditDao.selectAppListIdsByAppNumber(appNumber);
    UserSession userSession = securityContext.getUserSession();
    String name = userSession.name();
    String userId = userSession.userId();
    appIds.forEach(id -> {
      auditDao.insert(id, name, userId, status, Timestamp.valueOf(
          DateTimeUtil.dateToLocalDateTimeUtc(new Date())));
    });
  }
}
