package com.zioinfo.hrm.attendance;

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

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

@Service
@RequiredArgsConstructor
public class AttendanceService {

    private final AttendanceMapper attendanceMapper;

    public List<Map<String, Object>> getByEmpAndMonth(Long empId, int year, int month) {
        return attendanceMapper.findByEmpAndMonth(empId, year, month);
    }

    public Map<String, Object> listAll(LocalDate date, Long deptId, int page, int size) {
        int offset = (page - 1) * size;
        List<Map<String, Object>> rows = attendanceMapper.findAll(date, deptId, offset, size);
        Map<String, Object> r = new HashMap<>();
        r.put("items", rows);
        return r;
    }

    @Transactional
    public void checkIn(Long empId, String actor) {
        Map<String, Object> rec = new HashMap<>();
        rec.put("empId", empId);
        rec.put("checkInTime", LocalDateTime.now());
        rec.put("workDate", LocalDate.now());
        rec.put("createdBy", actor);
        attendanceMapper.checkIn(rec);
    }

    @Transactional
    public void checkOut(Long empId) {
        Map<String, Object> rec = new HashMap<>();
        rec.put("empId", empId);
        rec.put("checkOutTime", LocalDateTime.now());
        rec.put("workDate", LocalDate.now());
        attendanceMapper.checkOut(rec);
    }

    public List<Map<String, Object>> getLeaves(Long empId, String status, int year) {
        return attendanceMapper.findLeaves(empId, status, year);
    }

    @Transactional
    public void applyLeave(Long empId, Map<String, Object> leave, String actor) {
        leave.put("empId", empId);
        leave.put("status", "PENDING");
        leave.put("createdBy", actor);
        attendanceMapper.insertLeave(leave);
    }

    @Transactional
    public void approveLeave(Long id, String status, String approver) {
        attendanceMapper.updateLeaveStatus(id, status, approver);
    }

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

    public List<Map<String, Object>> getLeaveTypes() {
        return attendanceMapper.findLeaveTypes();
    }

    public List<Map<String, Object>> getOvertime(Long empId, int year, int month) {
        return attendanceMapper.findOvertime(empId, year, month);
    }

    @Transactional
    public void addOvertime(Long empId, Map<String, Object> ot, String actor) {
        ot.put("empId", empId);
        ot.put("createdBy", actor);
        attendanceMapper.insertOvertime(ot);
    }
}
