package ru.kayashov.bar.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PutMapping;
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 ru.kayashov.bar.controller.dto.ingredient.IngredientResponseDto;
import ru.kayashov.bar.controller.dto.ingredient.IngredientSimpleResponseDto;
import ru.kayashov.bar.controller.dto.ingredient.TypeResponseDto;
import ru.kayashov.bar.repository.TypeRepository;
import ru.kayashov.bar.service.IngredientService;

import java.util.List;

@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping("/api/ingredient")
@RequiredArgsConstructor
public class IngredientController {

    private final IngredientService ingredientService;
    private final TypeRepository typeRepository;

    @GetMapping("/all")
    public List<IngredientResponseDto> getIngredients() {
        return ingredientService.getAll();
    }

    @GetMapping("/simple")
    public List<IngredientSimpleResponseDto> getIngredientStringList() {
        return ingredientService.getAllSimple();
    }

    @GetMapping("/type")
    public List<TypeResponseDto> getTypes() {
        return typeRepository.findAll().stream()
                .map(TypeResponseDto::mapToDto)
                .toList();
    }

    @PatchMapping
    public ResponseEntity<?> saveChangeForType(@RequestBody IngredientResponseDto dto) {
        if(ingredientService.saveChange(dto)) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping
    public IngredientResponseDto getIngredient(@RequestParam Long id) {
        return IngredientResponseDto.mapToDto(ingredientService.getIngredientById(id));
    }

    @DeleteMapping
    public void deleteIngredient(@RequestParam Long id) {
        ingredientService.changeBarIngredient(id, false);
    }

    @PutMapping
    public void putIngredient(@RequestParam Long id) {
        ingredientService.changeBarIngredient(id, true);
    }
}
