package com.kalyshev.yan.coffee.controller;

import com.kalyshev.yan.WebConfiguration;
import com.kalyshev.yan.coffee.service.CoffeeService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(WebConfiguration.REST_API + "/coffee")
public class CoffeeController {
    private final CoffeeService coffeeService;
    public CoffeeController(CoffeeService coffeeService) {
        this.coffeeService = coffeeService;
    }
    @GetMapping("/{id}")
    public CoffeeDto getCoffee(@PathVariable Long id) {
        return new CoffeeDto(coffeeService.findCoffee(id));
    }
    @GetMapping("/")
    public List<CoffeeDto> getAllCoffees(
            @RequestParam(value = "pageNo", defaultValue = "1", required = false) int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            @RequestParam(value = "sortBy", defaultValue = "id", required = false) String sortBy,
            @RequestParam(value = "sortDir", defaultValue = "asc", required = false) String sortDir
    ){
        return coffeeService.findAllCoffees(pageNo-1, pageSize, sortBy, sortDir);
    }
    @PostMapping("/")
    public CoffeeDto createCoffee(@RequestBody @Valid CoffeeDto coffeeDto) {
        return new CoffeeDto(coffeeService.addCoffee(coffeeDto.getName(), coffeeDto.getCost(), coffeeDto.getIngredients()));
    }
    @PutMapping("/{id}")
    public CoffeeDto updateCoffee(@PathVariable Long id,
                                    @RequestBody @Valid CoffeeDto coffeeDto) {
        return new CoffeeDto(coffeeService.updateCoffee(id, coffeeDto.getName(), coffeeDto.getCost(), coffeeDto.getIngredients()));
    }
    @DeleteMapping("/{id}")
    public CoffeeDto deleteCoffee(@PathVariable Long id) {
        return new CoffeeDto(coffeeService.deleteCoffee(id));
    }
    @DeleteMapping("/")
    public void deleteAllCoffees() {
        coffeeService.deleteAllCoffees();
    }
}