package com.example.backend.books.api;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.backend.books.model.BookEntity;
import com.example.backend.books.service.BookService;
import com.example.backend.core.configuration.Constants;
import com.example.backend.core.session.SessionCart;
import com.example.backend.orders.api.BookCountDto;

@Controller
@RequestMapping(ProductCardController.URL)
public class ProductCardController {
    public static final String URL = "/product-card";

    private static final String CARD_VIEW = "product-card";

    private static final String CART_ATTRIBUTE = "cart";

    private final BookService bookService;
    private final ModelMapper modelMapper;
    private final SessionCart cart;

    public ProductCardController(
            BookService bookService,
            ModelMapper modelMapper,
            SessionCart cart) {
        this.bookService = bookService;
        this.modelMapper = modelMapper;
        this.cart = cart;
    }

    private BookDto toBookDto(BookEntity entity) {
        return modelMapper.map(entity, BookDto.class);
    }

    @GetMapping("/{id}")
    public String getProductCard(@PathVariable(name = "id") Long id, Model model) {
        if (id <= 0) {
            throw new IllegalArgumentException();
        }
        model.addAttribute(CART_ATTRIBUTE, cart);
        model.addAttribute("book", bookService.get(id));
        return CARD_VIEW;
    }

    @PostMapping("/{id}")
    public String addCartItem(@PathVariable(name = "id") Long id, Model model) {
        if (id <= 0) {
            throw new IllegalArgumentException();
        }
        BookEntity book = bookService.get(id);
        BookCountDto bookCountDto = new BookCountDto();
        bookCountDto.setBook(toBookDto(book));
        bookCountDto.setCount(1);
        cart.put(id, bookCountDto);
        return Constants.REDIRECT_VIEW + URL + "/" + id;
    }
}
