package com.eactive.testmaster.loadtest.controller;

import com.eactive.testmaster.common.util.SecurityUtil;
import com.eactive.testmaster.loadtest.dto.LoadTestDTO;
import com.eactive.testmaster.loadtest.entity.LoadTest;
import com.eactive.testmaster.loadtest.mapper.LoadTestMapper;
import com.eactive.testmaster.loadtest.service.LoadTestMgmtService;
import com.eactive.testmaster.user.entity.StaffUser;
import com.eactive.testmaster.user.service.UserService;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;

@RestController
@RequestMapping("/mgmt/load_test")
public class LoadTestMgmtController {

    private final LoadTestMgmtService loadTestMgmtService;

    private final LoadTestMapper loadTestMapper;

    private final UserService userService;

    public LoadTestMgmtController(LoadTestMgmtService loadTestMgmtService, LoadTestMapper loadTestMapper, UserService userService) {
        this.loadTestMgmtService = loadTestMgmtService;
        this.loadTestMapper = loadTestMapper;
        this.userService = userService;
    }

    @GetMapping("/list.do")
    public ResponseEntity<List<LoadTestDTO>> list() {
        List<LoadTest> list = loadTestMgmtService.findAll();
        return ResponseEntity.ok(loadTestMapper.toDtoList(list));
    }

    @PostMapping("/create.do")
    public ResponseEntity<LoadTestDTO> createScenario(@RequestBody LoadTestDTO loadTestDto) {
        LoadTest loadTest = loadTestMapper.map(loadTestDto);
        StaffUser user = userService.findByEsntlId(SecurityUtil.getCurrentUserEsntlId());
        loadTest.setOwner(user);
        LoadTest createdScenario = loadTestMgmtService.createLoadTest(loadTest);
        return new ResponseEntity<>(loadTestMapper.map(createdScenario), HttpStatus.CREATED);
    }

    @PostMapping("/update.do")
    public ResponseEntity<LoadTestDTO> updateScenario(@RequestBody LoadTestDTO loadTestDTO) {
        LoadTest updatedLoadTest = loadTestMapper.map(loadTestDTO);
        LoadTest updatedScenario = loadTestMgmtService.updateLoadTest(loadTestDTO.getId(), updatedLoadTest);
        return ResponseEntity.ok(loadTestMapper.map(updatedScenario));
    }

    @PostMapping("/delete.do")
    public ResponseEntity<Void> deleteScenario(@RequestBody LoadTestDTO loadTestDto) {
        loadTestMgmtService.deleteLoadTest(loadTestDto.getId());
        return ResponseEntity.ok().build();
    }
}
