package com.cloudhandson.vpdbackoffice.config;

import com.cloudhandson.vpdbackoffice.service.PermissionService;
import com.cloudhandson.vpdbackoffice.service.GroupService;
import com.cloudhandson.vpdbackoffice.service.UserService;
import java.sql.Connection;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class DbPoolWarmup {

  private static final Logger log = LoggerFactory.getLogger(DbPoolWarmup.class);
  private final DataSource dataSource;
  private final UserService userService;
  private final GroupService groupService;
  private final PermissionService permissionService;

  public DbPoolWarmup(
      DataSource dataSource,
      UserService userService,
      GroupService groupService,
      PermissionService permissionService
  ) {
    this.dataSource = dataSource;
    this.userService = userService;
    this.groupService = groupService;
    this.permissionService = permissionService;
  }

  @EventListener(ApplicationReadyEvent.class)
  public void warmup() {
    try (Connection ignored = dataSource.getConnection()) {
      log.info("Backoffice DB pool warmed up");
      warmupBackofficeCatalog();
    } catch (Exception exception) {
      log.warn("Backoffice DB pool warm-up failed: {}", exception.getMessage());
    }
  }

  private void warmupBackofficeCatalog() {
    long started = System.nanoTime();
    userService.findAll();
    userService.findUserRoles();
    groupService.findAll();
    groupService.findGroupUsers();
    groupService.findGroupRoles();
    permissionService.findRoles();
    permissionService.findPermissionViews();
    log.info("Identity catalog cache warmed up in {}ms", (System.nanoTime() - started) / 1_000_000);
  }
}
