package com.platform2easy.genesis.web.controller;

import com.platform2easy.genesis.domain.model.Orderbook;
import com.platform2easy.genesis.domain.service.OrderbookService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@RestController
@RequestMapping("/api/orderbook")
@AllArgsConstructor
public class OrderbookController {

    private final OrderbookService service;

    // GET /api/orderbook: Lista todos
    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<Orderbook> listAll() {
        return service.listarTodos();
    }

    // GET /api/orderbook/{id}: Busca por ID
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Orderbook getById(@PathVariable Long id) {
        return service.buscarPorId(id);
    }

    // POST /api/orderbook: Cria um novo registro
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Orderbook create(@RequestBody Orderbook orderbook) {
        orderbook.setId(null);
        return service.salvar(orderbook);
    }

    // PUT /api/orderbook/{id}: Atualiza um registro existente
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Orderbook update(@PathVariable Long id, @RequestBody Orderbook orderbook) {
        orderbook.setId(id);
        return service.salvar(orderbook);
    }

    // DELETE /api/orderbook/{id}: Deleta um registro
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        service.deletarPorId(id);
    }

    @GetMapping(params = "isToken")
    @ResponseStatus(HttpStatus.OK)
    public List<Orderbook> listByIsToken(@RequestParam("isToken") Integer isToken) {
        if (isToken == null || (isToken != 0 && isToken != 1)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "isToken must be 0 or 1");
        }
        return service.listarPorIsToken(isToken == 1);
    }
}