package com.nisum.servlet;

import com.nisum.dao.CartDAO;
import com.nisum.model.ShoppingCart;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AddToCartServlet extends HttpServlet {
    private final CartDAO cartDAO = new CartDAO();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        req.setCharacterEncoding("UTF-8");
        res.setContentType("text/plain");
        try {
            String userIdStr = req.getParameter("userId");
            String productIdStr = req.getParameter("productId");
            String quantityStr = req.getParameter("quantity");
//            System.out.println(userIdStr + productIdStr + quantityStr);
            if (isEmpty(userIdStr) || isEmpty(productIdStr) || isEmpty(quantityStr)) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing or empty parameter(s).");
                return;
            }

            int userId = Integer.parseInt(userIdStr.trim());
            int productId = Integer.parseInt(productIdStr.trim());
            int quantity = Integer.parseInt(quantityStr.trim());
//            System.out.println(userId + productId + quantity);
            if (quantity <= 0) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Quantity must be greater than 0.");
                return;
            }

            ShoppingCart cart = cartDAO.getOrCreateCart(userId);
            System.out.println("item created");
            cartDAO.addToCart(cart.getCartId(), productId, quantity);

            res.setStatus(HttpServletResponse.SC_OK);
            res.getWriter().write("Item added to cart successfully.");
        } catch (NumberFormatException nfe) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid number format.");
        } catch (Exception e) {
            e.printStackTrace();  // Better: use logging framework
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while adding to cart.");
        }
    }

    // Optional override to avoid HTTP 405 for GET requests
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "GET method not supported. Use POST.");
    }

    private boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
}
