package com.eactive.testmaster.client.controller;

import com.eactive.testmaster.client.dto.ApiScenarioDTO;
import com.eactive.testmaster.client.entity.ApiScenario;
import com.eactive.testmaster.client.mapper.ApiScenarioMapper;
import com.eactive.testmaster.client.service.ApiScenarioMgmtService;
import com.eactive.testmaster.common.util.SecurityUtil;
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/api_scenario")
public class ApiScenarioMgmtController {

    private final ApiScenarioMgmtService apiScenarioMgmtService;

    private final ApiScenarioMapper apiScenarioMapper;

    private final UserService userService;

    public ApiScenarioMgmtController(ApiScenarioMgmtService apiScenarioMgmtService, ApiScenarioMapper apiScenarioMapper, UserService userService) {
        this.apiScenarioMgmtService = apiScenarioMgmtService;
        this.apiScenarioMapper = apiScenarioMapper;
        this.userService = userService;
    }

    @GetMapping("/list.do")
    public ResponseEntity<List<ApiScenarioDTO>> listScenarios() {
        List<ApiScenario> scenarios = apiScenarioMgmtService.findAll();
        return ResponseEntity.ok(apiScenarioMapper.toDtoList(scenarios));
    }

    @PostMapping("/create.do")
    public ResponseEntity<ApiScenarioDTO> createScenario(@RequestBody ApiScenarioDTO apiScenarioDto) {
        ApiScenario apiScenario = apiScenarioMapper.map(apiScenarioDto);
        StaffUser user = userService.findByEsntlId(SecurityUtil.getCurrentUserEsntlId());
        apiScenario.setOwner(user);
        ApiScenario createdScenario = apiScenarioMgmtService.createApiScenario(apiScenario);
        return new ResponseEntity<>(apiScenarioMapper.map(createdScenario), HttpStatus.CREATED);
    }


    @PostMapping("/update.do")
    public ResponseEntity<ApiScenarioDTO> updateScenario(@RequestBody ApiScenarioDTO apiScenarioDto) {
        ApiScenario updatedApiScenario = apiScenarioMapper.map(apiScenarioDto);
        ApiScenario updatedScenario = apiScenarioMgmtService.updateApiScenario(apiScenarioDto.getId(), updatedApiScenario);
        return ResponseEntity.ok(apiScenarioMapper.map(updatedScenario));
    }

    @PostMapping("/delete.do")
    public ResponseEntity<Void> deleteScenario(@RequestBody ApiScenarioDTO apiScenarioDto) {
        apiScenarioMgmtService.deleteApiScenario(apiScenarioDto.getId());
        return ResponseEntity.ok().build();
    }

}
