package premium_store.controller.controller;

import org.springframework.web.bind.annotation.*;
import premium_store.WebConfiguration;
import premium_store.controller.DTO.TankDTO;
import premium_store.service.NationService;
import premium_store.service.TankLevelService;
import premium_store.service.TankService;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping(WebConfiguration.REST_API + "/tank")
public class TankController {
    private final TankService tankService;
    private final TankLevelService tankLevelService;
    private final NationService nationService;

    public TankController(TankService tankService, TankLevelService tankLevelService, NationService nationService){
        this.tankService = tankService;
        this.tankLevelService = tankLevelService;
        this.nationService = nationService;
    }

    //аннотация PathVariable связывает значения id из URL и Long id
    @GetMapping("/{id}")
    public TankDTO getTank(@PathVariable Long id) {
        return new TankDTO(tankService.findTank(id));
    }

    //с помощью Java Stream преобразуем набор пришедших данных в объекты TankDTO
    @GetMapping("/")
    public List<TankDTO> getTanks() {
        return tankService.findAllTanks().stream()
                .map(TankDTO::new)
                .toList();
    }

    @GetMapping("/filteredList/")
    public List<TankDTO> getFilteredTanks(@RequestParam("nation") String nation,
                                          @RequestParam("firstLevel") int firstLevel,
                                          @RequestParam("secondLevel") int secondLevel) {
        return tankService.findListTank(nation, firstLevel, secondLevel).stream()
                .map(TankDTO::new)
                .toList();
    }

    @PostMapping("/")
    public TankDTO createTank(@RequestParam("firstName") String name,
                              @RequestParam("nationId") Long nationId,
                              @RequestParam("levelId") Long tankLevelId,
                              @RequestParam("cost") int cost
    ) {
        return new TankDTO(tankService.addTank(name, nationService.findNation(nationId), tankLevelService.findLevel(tankLevelId), cost));
    }

    @PutMapping("/{id}")
    public TankDTO updateTank(@PathVariable Long id,
                              @RequestParam("firstName") String name,
                              @RequestParam("nationId") Long nationId,
                              @RequestParam("levelId") Long tankLevelId,
                              @RequestParam("cost") int cost
    ) {
        return new TankDTO(tankService.updateTank(id, name, nationService.findNation(nationId), tankLevelService.findLevel(tankLevelId), cost));
    }

    @DeleteMapping("/{id}")
    public TankDTO deleteTank(@PathVariable Long id) {
        return new TankDTO(tankService.deleteTank(id));
    }
}
