package de.avatic.lcc.service.bulk.bulkImport;

import de.avatic.lcc.model.bulk.BulkInstruction;
import de.avatic.lcc.model.bulk.BulkInstructionType;
import de.avatic.lcc.model.db.materials.Material;
import de.avatic.lcc.repositories.MaterialRepository;
import de.avatic.lcc.util.exception.internalerror.ExcelValidationError;
import org.springframework.stereotype.Service;

@Service
public class MaterialBulkImportService {

    private final MaterialRepository materialRepository;

    public MaterialBulkImportService(MaterialRepository materialRepository) {
        this.materialRepository = materialRepository;
    }


    public void processMaterialInstructions(BulkInstruction<Material> instr) {
        BulkInstructionType instrType = instr.getType();
        Material material = instr.getEntity();


        if (instrType == BulkInstructionType.UPDATE) {
            updateMaterial(material);
        } else if (instrType == BulkInstructionType.DELETE) {
            deleteMaterial(material);
        }
    }

    private void updateMaterial(Material material) {
        var foundMaterial = materialRepository.getByPartNumber(material.getNormalizedPartNumber());

        if (foundMaterial.isEmpty()) {
            materialRepository.insert(material);
        } else {
            material.setId(foundMaterial.get().getId());
            materialRepository.update(material);
        }
    }

    private void deleteMaterial(Material material) {
        var foundMaterial = materialRepository.getByPartNumber(material.getNormalizedPartNumber());

        if (foundMaterial.isEmpty()) {
            throw new ExcelValidationError("Unable to delete. Material with part number " + material.getPartNumber() + " not found");
        } else {
            materialRepository.setDeprecatedById(foundMaterial.get().getId());
        }

    }
}
