package com.zioinfo.hrm.training;

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

    private final TrainingMapper trainingMapper;

    public Map<String, Object> listCourses(String keyword, String type, int page, int size) {
        int offset = (page - 1) * size;
        List<Map<String, Object>> rows = trainingMapper.findCourses(keyword, type, offset, size);
        long total = trainingMapper.countCourses(keyword, type);
        Map<String, Object> r = new HashMap<>();
        r.put("items", rows);
        r.put("total", total);
        return r;
    }

    public Map<String, Object> getCourse(Long id) {
        return trainingMapper.findCourseById(id);
    }

    @Transactional
    public void createCourse(Map<String, Object> course, String actor) {
        course.put("createdBy", actor);
        trainingMapper.insertCourse(course);
    }

    @Transactional
    public void updateCourse(Long id, Map<String, Object> course) {
        course.put("id", id);
        trainingMapper.updateCourse(course);
    }

    public List<Map<String, Object>> getEnrollments(Long empId, Long courseId, int year) {
        int y = year == 0 ? LocalDate.now().getYear() : year;
        return trainingMapper.findEnrollments(empId, courseId, y);
    }

    @Transactional
    public void enroll(Long empId, Long courseId, String actor) {
        Map<String, Object> enrollment = new HashMap<>();
        enrollment.put("empId", empId);
        enrollment.put("courseId", courseId);
        enrollment.put("status", "ENROLLED");
        enrollment.put("createdBy", actor);
        trainingMapper.insertEnrollment(enrollment);
    }

    @Transactional
    public void complete(Long enrollmentId) {
        trainingMapper.updateEnrollmentStatus(enrollmentId, "COMPLETED", LocalDate.now());
    }

    public Map<String, Object> getLegalStatus(Long empId, int year) {
        int y = year == 0 ? LocalDate.now().getYear() : year;
        return trainingMapper.getLegalTrainingStatus(empId, y);
    }

    public List<Map<String, Object>> getLegalCourses() {
        return trainingMapper.findLegalCourses();
    }
}
