package com.smartoffice.leave;

import com.smartoffice.auth.UserPrincipal;
import com.smartoffice.common.ApiResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/leave-requests")
public class LeaveController {
    private final LeaveService leaveService;

    public LeaveController(LeaveService leaveService) {
        this.leaveService = leaveService;
    }

    @PostMapping
    public ApiResponse<LeaveDto> create(@AuthenticationPrincipal UserPrincipal principal,
                                        @Valid @RequestBody LeaveRequestCreate request) {
        return ApiResponse.created(leaveService.create(principal.getUsername(), request));
    }

    @GetMapping("/my")
    public ApiResponse<List<LeaveDto>> myRequests(@AuthenticationPrincipal UserPrincipal principal) {
        return ApiResponse.ok(leaveService.myRequests(principal.getUsername()));
    }

    @GetMapping("/pending")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<LeaveDto>> pending() {
        return ApiResponse.ok(leaveService.pendingRequests());
    }

    @PostMapping("/{id}/approve")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<LeaveDto> approve(@AuthenticationPrincipal UserPrincipal principal,
                                         @PathVariable("id") Long id,
                                         @Valid @RequestBody DecisionRequest request) {
        return ApiResponse.ok(leaveService.approve(principal.getUsername(), id, request.getNote(), true));
    }

    @PostMapping("/{id}/reject")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<LeaveDto> reject(@AuthenticationPrincipal UserPrincipal principal,
                                        @PathVariable("id") Long id,
                                        @Valid @RequestBody DecisionRequest request) {
        return ApiResponse.ok(leaveService.approve(principal.getUsername(), id, request.getNote(), false));
    }
}
