package com.sn.sowsysrestapi.domain.service;

import com.sn.sowsysrestapi.domain.entity.Concern;
import com.sn.sowsysrestapi.domain.entity.Report;
import com.sn.sowsysrestapi.domain.exception.ConcernNotFoundException;
import com.sn.sowsysrestapi.domain.exception.EntityInUseException;
import com.sn.sowsysrestapi.domain.repository.ConcernRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

@Service
public class ConcernService {

    public static final String MSG_ENTITY_IN_USE = "Concern with ID %d can't be deleted." +
            " Reason: Other entity is using this entity.";

    @Autowired
    private ConcernRepo concernRepo;

    @Autowired
    private ReportService reportService;

    public Concern save(Long reportId, Concern concern){

        Report report = reportService.findOrFail(reportId);

        concern.setReport(report);

        return concernRepo.save(concern);

    }

    public void delete(Long id) {

        try {
            concernRepo.deleteById(id);
            concernRepo.flush();

        } catch (EmptyResultDataAccessException e) {
            throw new ConcernNotFoundException(id);

        } catch (DataIntegrityViolationException e) {
            throw new EntityInUseException(
                    String.format(MSG_ENTITY_IN_USE, id));
        }

    }

    public Concern findOrFail(Long id){
        return concernRepo.findById(id)
                .orElseThrow(() -> new ConcernNotFoundException(id));
    }


}
