package com.spring.domain.schedule.api;

import java.util.List;

import javax.validation.Valid;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.spring.domain.schedule.dto.ReScheduleJobRequest;
import com.spring.domain.schedule.dto.ScheduleJobResponse;
import com.spring.domain.schedule.service.FindScheduleJobService;
import com.spring.domain.schedule.service.ReScheduleJobService;
import com.spring.domain.schedule.service.ScheduleControlService;

import lombok.RequiredArgsConstructor;

@RequestMapping("/api/schedule")
@RestController
@RequiredArgsConstructor
public class ScheduleJobApi {
    
    private final FindScheduleJobService findScheduleJobService;
    private final ReScheduleJobService reScheduleJobService;
    private final ScheduleControlService scheduleControlService;

    @GetMapping
    @PreAuthorize("hasAnyRole('SUPER', 'ADMIN')")
    public List<ScheduleJobResponse> getAllJobs(@RequestParam(required = false) String groupName, @RequestParam(required = false) String jobName) {
        return findScheduleJobService.getAllJobs(groupName, jobName);
    }

    @GetMapping("/{groupName}/{jobName}")
    @PreAuthorize("hasAnyRole('SUPER', 'ADMIN')")
    public ScheduleJobResponse getJobDetail(@PathVariable String groupName, @PathVariable String jobName) {
        return findScheduleJobService.getJobDetail(groupName, jobName);
    }

    @GetMapping("/pause/{groupName}/{jobName}")
    @PreAuthorize("hasAnyRole('SUPER', 'ADMIN')")
    public void pauseJob(@PathVariable String groupName, @PathVariable String jobName) {
        scheduleControlService.pauseJob(groupName, jobName);
    }

    @GetMapping("/resume/{groupName}/{jobName}")
    @PreAuthorize("hasAnyRole('SUPER', 'ADMIN')")
    public void resumeJob(@PathVariable String groupName, @PathVariable String jobName) {
        scheduleControlService.resumeJob(groupName, jobName);
    }

    @GetMapping("/trigger/{groupName}/{jobName}")
    @PreAuthorize("hasAnyRole('SUPER', 'ADMIN')")
    public void triggerJob(@PathVariable String groupName, @PathVariable String jobName) {
        scheduleControlService.triggerJob(groupName, jobName);
    }

    @PostMapping("/reschedule")
    @PreAuthorize("hasAnyRole('SUPER', 'ADMIN')")
    public boolean rescheduleJob(@Valid @RequestBody ReScheduleJobRequest request) {
        return reScheduleJobService.rescheduleJob(request);
    }

}
