package com.psg.dlsysinfo.dl_sysinfo_server.service;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class CveStatisticsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void refreshStatistics() {
        String sql = """
            INSERT INTO cve_statistics (
                total, missing_title, missing_severity, missing_cvss_score,
                missing_cvss_vector, missing_references, missing_published_date,
                missing_description, missing_cwe, missing_cert_notes, missing_cert_alerts, missing_cisa_kev
            )
            SELECT
                (SELECT COUNT(*) FROM cves),
                (SELECT COUNT(*) FROM cves WHERE title IS NULL OR title = ''),
                (SELECT COUNT(*) FROM cves WHERE (severity_v3 IS NULL OR severity_v3 = '') AND (severity_v2 IS NULL OR severity_v2 = '')),
                (SELECT COUNT(*) FROM cves WHERE cvss_score IS NULL AND cvss_score_v2 IS NULL AND cvss_score_v3 IS NULL AND cvss_score_v4 IS NULL),
                (SELECT COUNT(*) FROM cves WHERE cvss_vector IS NULL AND cvss_vector_v2 IS NULL AND cvss_vector_v3 IS NULL AND cvss_vector_v4 IS NULL),
                (SELECT COUNT(*) FROM cves WHERE `references` IS NULL OR `references` = ''),
                (SELECT COUNT(*) FROM cves WHERE published_date IS NULL),
                (SELECT COUNT(*) FROM cves WHERE description IS NULL OR description = ''),
                (SELECT COUNT(*) FROM cves WHERE cwe_ids IS NULL OR cwe_ids = ''),
                (SELECT COUNT(*) FROM cves WHERE hasCertNotes = 0),
                (SELECT COUNT(*) FROM cves WHERE hasCertAlerts = 0),
                (SELECT COUNT(*) FROM cves WHERE hasKev = 0)
            """;

        jdbcTemplate.execute("DELETE FROM cve_statistics"); // clear existing row(s)
        jdbcTemplate.execute(sql);
    }
}
