package ervu_business_metrics.dao;

import java.util.List;

import ervu_business_metrics.config.KafkaEnabledCondition;
import ervu_business_metrics.model.sso.UserAccount;
import ervu_business_metrics.model.sso.UserSessionInfo;
import org.jooq.DSLContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Repository;
import ru.micord.webbpm.ervu.business_metrics.db_beans.auth.tables.records.ActiveSessionRecord;

import static ru.micord.webbpm.ervu.business_metrics.db_beans.auth.Tables.ACTIVE_SESSION;

/**
 * @author Adel Kalimullin
 */
@Repository
@Conditional(KafkaEnabledCondition.class)
public class ActiveSessionDao {
  private final DSLContext dsl;

  public ActiveSessionDao(DSLContext dsl) {
    this.dsl = dsl;
  }

  public void saveAll(List<UserSessionInfo> sessions) {
    List<ActiveSessionRecord> records = sessions.stream()
        .map(session -> {
          UserAccount userAccount = session.getUserIdentity().getUserAccount();
          ActiveSessionRecord record = dsl.newRecord(ACTIVE_SESSION);
          record.setSessionId(session.getSessionId());
          record.setDomainId(userAccount.getDomain().getId());
          record.setUserId(userAccount.getId());
          record.setIpAddress(session.getIp());
          return record;
        })
        .toList();

    dsl.batchInsert(records).execute();
  }

  public void clear() {
    dsl.truncate(ACTIVE_SESSION).execute();
  }
}
