package com.zioinfo.hrm.training;

import com.zioinfo.hrm.common.ApiResponse;
import com.zioinfo.hrm.common.AuthSupport;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/hrm/training")
@RequiredArgsConstructor
public class TrainingController {

    private final TrainingService trainingService;

    @GetMapping("/courses")
    public ApiResponse<Map<String, Object>> listCourses(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String type,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ApiResponse.ok(trainingService.listCourses(keyword, type, page, size));
    }

    @GetMapping("/courses/{id}")
    public ApiResponse<Map<String, Object>> getCourse(@PathVariable Long id) {
        return ApiResponse.ok(trainingService.getCourse(id));
    }

    @PostMapping("/courses")
    public ApiResponse<Void> createCourse(@RequestBody Map<String, Object> course, Authentication auth) {
        AuthSupport.requireManager(auth);
        trainingService.createCourse(course, AuthSupport.actor(auth));
        return ApiResponse.ok(null);
    }

    @PutMapping("/courses/{id}")
    public ApiResponse<Void> updateCourse(@PathVariable Long id, @RequestBody Map<String, Object> course,
                                           Authentication auth) {
        AuthSupport.requireManager(auth);
        trainingService.updateCourse(id, course);
        return ApiResponse.ok(null);
    }

    @GetMapping("/enrollments")
    public ApiResponse<List<Map<String, Object>>> getEnrollments(
            @RequestParam(required = false) Long empId,
            @RequestParam(required = false) Long courseId,
            @RequestParam(defaultValue = "0") int year) {
        return ApiResponse.ok(trainingService.getEnrollments(empId, courseId, year));
    }

    @PostMapping("/enrollments/{empId}/{courseId}")
    public ApiResponse<Void> enroll(@PathVariable Long empId, @PathVariable Long courseId, Authentication auth) {
        trainingService.enroll(empId, courseId, AuthSupport.actor(auth));
        return ApiResponse.ok(null);
    }

    @PostMapping("/enrollments/{id}/complete")
    public ApiResponse<Void> complete(@PathVariable Long id) {
        trainingService.complete(id);
        return ApiResponse.ok(null);
    }

    @GetMapping("/legal/{empId}")
    public ApiResponse<Map<String, Object>> legalStatus(
            @PathVariable Long empId, @RequestParam(defaultValue = "0") int year) {
        return ApiResponse.ok(trainingService.getLegalStatus(empId, year));
    }

    @GetMapping("/legal-courses")
    public ApiResponse<List<Map<String, Object>>> legalCourses() {
        return ApiResponse.ok(trainingService.getLegalCourses());
    }
}
