package com.zioinfo.hrm.recruitment;

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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class RecruitmentService {

    private final RecruitmentMapper recruitmentMapper;

    public Map<String, Object> listPostings(String status, String keyword, int page, int size) {
        int offset = (page - 1) * size;
        List<Map<String, Object>> rows = recruitmentMapper.findPostings(status, keyword, offset, size);
        long total = recruitmentMapper.countPostings(status, keyword);
        Map<String, Object> r = new HashMap<>();
        r.put("items", rows);
        r.put("total", total);
        return r;
    }

    public Map<String, Object> getPosting(Long id) {
        return recruitmentMapper.findPostingById(id);
    }

    @Transactional
    public void createPosting(Map<String, Object> posting, String actor) {
        posting.put("status", "DRAFT");
        posting.put("createdBy", actor);
        recruitmentMapper.insertPosting(posting);
    }

    @Transactional
    public void updatePosting(Long id, Map<String, Object> posting) {
        posting.put("id", id);
        recruitmentMapper.updatePosting(posting);
    }

    @Transactional
    public void publishPosting(Long id) {
        recruitmentMapper.updatePostingStatus(id, "PUBLISHED");
    }

    @Transactional
    public void closePosting(Long id) {
        recruitmentMapper.updatePostingStatus(id, "CLOSED");
    }

    public List<Map<String, Object>> getApplicants(Long postingId, String status) {
        return recruitmentMapper.findApplicants(postingId, status);
    }

    public Map<String, Object> getApplicant(Long id) {
        return recruitmentMapper.findApplicantById(id);
    }

    @Transactional
    public void addApplicant(Long postingId, Map<String, Object> applicant, String actor) {
        applicant.put("postingId", postingId);
        applicant.put("status", "APPLIED");
        applicant.put("createdBy", actor);
        recruitmentMapper.insertApplicant(applicant);
    }

    @Transactional
    public void updateApplicantStatus(Long id, String status, String memo) {
        recruitmentMapper.updateApplicantStatus(id, status, memo);
    }

    public List<Map<String, Object>> getInterviews(Long postingId, Long applicantId) {
        return recruitmentMapper.findInterviews(postingId, applicantId);
    }

    @Transactional
    public void scheduleInterview(Map<String, Object> interview, String actor) {
        interview.put("createdBy", actor);
        recruitmentMapper.insertInterview(interview);
    }

    @Transactional
    public void updateInterview(Long id, Map<String, Object> interview) {
        interview.put("id", id);
        recruitmentMapper.updateInterview(interview);
    }
}
