package org.hso.ecommerce.components;

import org.hso.ecommerce.app.config.AppSettings;
import org.hso.ecommerce.app.config.YAMLData;
import org.hso.ecommerce.entities.supplier.Supplier;
import org.hso.ecommerce.repos.supplier.SupplierRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Optional;

@Component
public class SupplierInitializer {

    @Autowired
    private final SupplierRepository supplierRepository = null;

    @Autowired
    private final AppSettings appSettings = null;

    @PostConstruct
    public void init() {
        for (YAMLData.Supplier cfg : appSettings.getSuppliers()) {
            Optional<Supplier> sup = supplierRepository.findByUuid(cfg.id);

            Supplier supplier;
            if (sup.isPresent()) {
                supplier = sup.get();
                supplier.name = cfg.name;
                supplier.apiUrl = cfg.apiURL;
            } else {
                supplier = new Supplier();
                supplier.uuid = cfg.id;
                supplier.apiUrl = cfg.apiURL;
                supplier.name = cfg.name;
            }
            supplierRepository.save(supplier);
        }
    }

}
