package com.psg.dlsysinfo.dl_sysinfo_server.service;

import com.psg.dlsysinfo.dl_sysinfo_server.entity.InstalledSoftware;
import com.psg.dlsysinfo.dl_sysinfo_server.repository.InstalledSoftwareRepository;
import com.psg.dlsysinfo.dl_sysinfo_server.util.NormalizationUtils;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class NormalizationService {

    private final InstalledSoftwareRepository installedSoftwareRepository;

    @Transactional
    public int normalizeInstalledSoftware() {
        List<InstalledSoftware> all = installedSoftwareRepository.findAll();
        int updatedCount = 0;

        for (InstalledSoftware app : all) {
            String normPub = NormalizationUtils.simplifyPublisher(app.getPublisher());
            String normProd = NormalizationUtils.normalizeProduct(app.getAppName());
            String normName = NormalizationUtils.normalize(app.getAppName());

            boolean changed = false;

            if (!normPub.equals(app.getNormalizedPublisher())) {
                app.setNormalizedPublisher(normPub);
                changed = true;
            }

            if (!normProd.equals(app.getNormalizedProduct())) {
                app.setNormalizedProduct(normProd);
                changed = true;
            }

            if (!normName.equals(app.getNormalizedAppName())) {
                app.setNormalizedAppName(normName);
                changed = true;
            }

            if (changed) updatedCount++;
        }

        installedSoftwareRepository.saveAll(all);
        return updatedCount;
    }
}
