package com.zioinfo.hrm.employee;

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.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/hrm/employees")
@RequiredArgsConstructor
public class EmployeeController {

    private final EmployeeService employeeService;

    @GetMapping
    public ApiResponse<Map<String, Object>> list(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long deptId,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ApiResponse.ok(employeeService.list(keyword, deptId, status, page, size));
    }

    @GetMapping("/{id}")
    public ApiResponse<Employee> getById(@PathVariable Long id) {
        return ApiResponse.ok(employeeService.getById(id));
    }

    @PostMapping
    public ApiResponse<Employee> create(@RequestBody Employee emp, Authentication auth) {
        AuthSupport.requireManager(auth);
        return ApiResponse.ok(employeeService.create(emp, AuthSupport.actor(auth)));
    }

    @PutMapping("/{id}")
    public ApiResponse<Employee> update(@PathVariable Long id, @RequestBody Employee emp, Authentication auth) {
        AuthSupport.requireManager(auth);
        return ApiResponse.ok(employeeService.update(id, emp));
    }

    @PostMapping("/{id}/retire")
    public ApiResponse<Void> retire(@PathVariable Long id,
                                     @RequestParam(required = false) String retireDate,
                                     Authentication auth) {
        AuthSupport.requireManager(auth);
        LocalDate date = retireDate != null ? LocalDate.parse(retireDate) : LocalDate.now();
        employeeService.retire(id, date);
        return ApiResponse.ok(null);
    }

    @GetMapping("/{id}/career")
    public ApiResponse<List<Map<String, Object>>> getCareer(@PathVariable Long id) {
        return ApiResponse.ok(employeeService.getCareer(id));
    }

    @PostMapping("/{id}/career")
    public ApiResponse<Void> addCareer(@PathVariable Long id, @RequestBody Map<String, Object> career) {
        employeeService.addCareer(id, career);
        return ApiResponse.ok(null);
    }

    @GetMapping("/{id}/certs")
    public ApiResponse<List<Map<String, Object>>> getCerts(@PathVariable Long id) {
        return ApiResponse.ok(employeeService.getCerts(id));
    }

    @PostMapping("/{id}/certs")
    public ApiResponse<Void> addCert(@PathVariable Long id, @RequestBody Map<String, Object> cert) {
        employeeService.addCert(id, cert);
        return ApiResponse.ok(null);
    }
}
