package com.zioinfo.hrm.payroll;

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 PayrollService {

    private final PayrollMapper payrollMapper;

    public Map<String, Object> list(int year, int month, Long deptId, int page, int size) {
        int offset = (page - 1) * size;
        List<Map<String, Object>> rows = payrollMapper.findPayrolls(year, month, deptId, offset, size);
        long total = payrollMapper.countPayrolls(year, month, deptId);
        Map<String, Object> result = new HashMap<>();
        result.put("items", rows);
        result.put("total", total);
        return result;
    }

    public Map<String, Object> getPayslip(Long empId, int year, int month) {
        return payrollMapper.findPayslip(empId, year, month);
    }

    public List<Map<String, Object>> getPayslipsByEmp(Long empId, int year) {
        return payrollMapper.findPayslipsByEmp(empId, year);
    }

    @Transactional
    public void processPayroll(int year, int month, String actor) {
        // 급여 지급 처리 로직 (실제 계산은 급여항목 기반)
        Map<String, Object> payroll = new HashMap<>();
        payroll.put("year", year);
        payroll.put("month", month);
        payroll.put("status", "PROCESSED");
        payroll.put("processedBy", actor);
        payroll.put("processedAt", LocalDate.now());
        payrollMapper.insertPayroll(payroll);
    }

    @Transactional
    public void approvePayroll(Long id) {
        payrollMapper.updatePayrollStatus(id, "APPROVED");
    }

    public Map<String, Object> getSalary(Long empId) {
        return payrollMapper.findSalaryByEmpId(empId);
    }

    @Transactional
    public void upsertSalary(Long empId, Map<String, Object> salary) {
        salary.put("empId", empId);
        payrollMapper.upsertSalary(salary);
    }

    public Map<String, Object> getYearlySummary(Long empId, int year) {
        return payrollMapper.getYearlySummary(empId, year);
    }

    public List<Map<String, Object>> getSalaryItems() {
        return payrollMapper.findSalaryItems();
    }
}
