package com.example.springip.lab3.service;

import com.example.springip.lab3.dao.CompanyRepository;
import com.example.springip.lab3.dao.EmployeeRepository;
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 {
    private CompanyRepository companyRepository;
    private EmployeeRepository employeeRepository;
    public CompanyService(CompanyRepository companyRepository, EmployeeRepository employeeRepository) {
        this.companyRepository = companyRepository;
        this.employeeRepository = employeeRepository;
    }

    @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);
        companyRepository.save(company);
        return company;
    }

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

    @Transactional(readOnly = true)
    public List<Company> findAllCompanies() {
        return companyRepository.findAll();
    }

    @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 companyRepository.save(currentCompany);
    }

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

    @Transactional
    public void deleteAllCompanies() {
        companyRepository.deleteAll();
    }

    @Transactional
    public Employee addNewEmployee(Long id, Employee employee) {
        Company currentCompany = findCompany(id);
        currentCompany.addNewEmployee(employee);
        companyRepository.save(currentCompany);
        return employee;
    }

    @Transactional
    public Employee deleteEmployee(Long id, Employee employee) {
        Company currentCompany = findCompany(id);
        currentCompany.deleteEmployee(employee);
        return employeeRepository.save(employee);
    }
}
