package com.iqser.red.service.persistence.management.v1.processor.lifecycle;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import com.iqser.red.service.persistence.management.v1.processor.service.persistence.AppVersionPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.utils.TenantUtils;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantcommons.TenantProvider;

import jakarta.validation.ConstraintViolationException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@RequiredArgsConstructor
public class AppVersionTracker {

    @Value("${BACKEND_APP_VERSION:}")
    private String appVersion;

    @Value("${LAYOUT_PARSER_VERSION:}")
    private String layoutParserVersion;

    private final AppVersionPersistenceService appVersionPersistenceService;
    private final TenantProvider tenantProvider;


    @EventListener(ApplicationReadyEvent.class)
    public void trackAppVersion() {

        tenantProvider.getTenants()
                .forEach(tenant -> {

                    if (!TenantUtils.isTenantReadyForPersistence(tenant)) {
                        return;
                    }

                    if (appVersion.isBlank() || layoutParserVersion.isBlank()) {
                        log.info("No app version or layout parser version was provided. Version tracking skipped. ");
                        return;
                    }

                    TenantContext.setTenantId(tenant.getTenantId());

                    try {
                        if (appVersionPersistenceService.insertIfNotExists(appVersion, layoutParserVersion)) {
                            log.info("Started with new app version {} / layout parser version {}.", appVersion, layoutParserVersion);
                        }
                    } catch (ConstraintViolationException cve) {
                        log.error("Validation failed for app version {} / layout parser version {}.", appVersion, layoutParserVersion, cve);
                    } catch (Exception e) {
                        log.error("Failed to track app version {} / layout parser version {}.", appVersion, layoutParserVersion, e);
                    }
                });
    }

}
