package kr.itn.itnhub.contact;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
public class ContactService {

    private static final Set<String> CATEGORIES = Set.of("APPLICANT", "MJ", "LAWYER", "OPERATOR");

    private final ContactMapper mapper;

    public ContactService(ContactMapper mapper) {
        this.mapper = mapper;
    }

    public List<Contact> findAll(String category) {
        if (category != null && !CATEGORIES.contains(category)) {
            throw new InvalidContactException("구분 값이 올바르지 않습니다: " + category);
        }
        return mapper.findAll(category);
    }

    @Transactional
    public Contact create(ContactRequest request) {
        validateCategory(request.category());

        Contact contact = new Contact();
        applyRequest(contact, request);
        mapper.insert(contact);
        return mapper.findById(contact.getId());
    }

    @Transactional
    public Contact update(Long id, ContactRequest request) {
        validateCategory(request.category());

        Contact existing = mapper.findById(id);
        if (existing == null) {
            throw new ContactNotFoundException("담당자를 찾을 수 없습니다: " + id);
        }
        applyRequest(existing, request);
        mapper.update(existing);
        return mapper.findById(id);
    }

    /** FK는 on delete set null이므로, 이 담당자를 배정으로 쓰던 기관들은 자동으로 미지정이 된다. */
    @Transactional
    public void delete(Long id) {
        Contact existing = mapper.findById(id);
        if (existing == null) {
            throw new ContactNotFoundException("담당자를 찾을 수 없습니다: " + id);
        }
        mapper.delete(id);
    }

    private void applyRequest(Contact contact, ContactRequest request) {
        contact.setCategory(request.category());
        contact.setName(request.name());
        contact.setAffiliation(request.affiliation());
        contact.setDeptName(request.deptName());
        contact.setTitle(request.title());
        contact.setPhone(request.phone());
        contact.setEmail(request.email());
    }

    private void validateCategory(String category) {
        if (!CATEGORIES.contains(category)) {
            throw new InvalidContactException("구분 값이 올바르지 않습니다: " + category);
        }
    }
}
