package com.example.springip.lab3.service;

import com.example.springip.lab3.models.Company;
import com.example.springip.lab3.models.Employee;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CompanyService {
    @PersistenceContext
    private EntityManager em;

    @Transactional
    public Company addCompany(String name) {
        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("Student name is null or empty");
        }
        final Company company = new Company(name);
        em.persist(company);
        return company;
    }

    @Transactional(readOnly = true)
    public Company findCompany(Long id) {
        final Company company = em.find(Company.class, id);
        if (company == null) {
            throw new EntityNotFoundException(String.format("Company with id [%s] is not found", id));
        }
        return company;
    }

    @Transactional(readOnly = true)
    public Company findCompany(String name) {
        Company company = em.createQuery("select c from Company c WHERE c.name = :companyName", Company.class)
                .setParameter("companyName",name)
                .getSingleResult();
        if (company == null) {
            throw new EntityNotFoundException(String.format("Company with name [%s] is not found", name));
        }
        return company;
    }

    @Transactional(readOnly = true)
    public List<Company> findAllCompanies() {
        return em.createQuery("select c from Company c", Company.class)
                .getResultList();
    }

    @Transactional
    public Company updateCompany(Long id, String name) {
        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("Company name is null or empty");
        }
        final Company currentCompany = findCompany(id);
        currentCompany.setName(name);

        return em.merge(currentCompany);
    }

    @Transactional
    public Company deleteCompany(Long id) {
        final Company currentCompany = findCompany(id);
        em.remove(currentCompany);
        return currentCompany;
    }

    @Transactional
    public void deleteAllCompanies() {
        em.createQuery("delete from Company").executeUpdate();
    }

    @Transactional
    public void addNewEmployee(Long id, Employee employee) {
        Company currentCompany = findCompany(id);
        currentCompany.addNewEmployee(employee);
        em.merge(currentCompany);
    }

    @Transactional
    public void deleteEmployee(Long id, Employee employee) {
        Company currentCompany = findCompany(id);
        currentCompany.deleteEmployee(employee);
        em.merge(employee);
    }
}
