package com.zioinfo.hrm.performance;

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

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

@Service
@RequiredArgsConstructor
public class PerformanceService {

    private final PerformanceMapper performanceMapper;

    public Map<String, Object> listReviews(int year, Long empId, String status, int page, int size) {
        int offset = (page - 1) * size;
        int y = year == 0 ? LocalDate.now().getYear() : year;
        List<Map<String, Object>> rows = performanceMapper.findReviews(y, empId, status, offset, size);
        long total = performanceMapper.countReviews(y, empId, status);
        Map<String, Object> r = new HashMap<>();
        r.put("items", rows);
        r.put("total", total);
        return r;
    }

    public Map<String, Object> getReview(Long id) {
        return performanceMapper.findReviewById(id);
    }

    @Transactional
    public void createReview(Map<String, Object> review, String actor) {
        review.put("status", "DRAFT");
        review.put("createdBy", actor);
        performanceMapper.insertReview(review);
    }

    @Transactional
    public void updateReview(Long id, Map<String, Object> review) {
        review.put("id", id);
        performanceMapper.updateReview(review);
    }

    @Transactional
    public void submitReview(Long id) {
        performanceMapper.updateReviewStatus(id, "SUBMITTED");
    }

    @Transactional
    public void approveReview(Long id) {
        performanceMapper.updateReviewStatus(id, "COMPLETED");
    }

    public List<Map<String, Object>> getGoals(Long empId, int year) {
        int y = year == 0 ? LocalDate.now().getYear() : year;
        return performanceMapper.findGoals(empId, y);
    }

    @Transactional
    public void createGoal(Long empId, Map<String, Object> goal, String actor) {
        goal.put("empId", empId);
        goal.put("createdBy", actor);
        performanceMapper.insertGoal(goal);
    }

    @Transactional
    public void updateGoal(Long id, Map<String, Object> goal) {
        goal.put("id", id);
        performanceMapper.updateGoal(goal);
    }

    public List<Map<String, Object>> getCompetencies(Long empId, int year) {
        int y = year == 0 ? LocalDate.now().getYear() : year;
        return performanceMapper.findCompetencies(empId, y);
    }

    @Transactional
    public void addCompetencyScore(Long empId, Map<String, Object> score, String actor) {
        score.put("empId", empId);
        score.put("evaluator", actor);
        performanceMapper.insertCompetencyScore(score);
    }
}
