package com.nisum.servlet;

import com.nisum.dao.ProductDAO;
import com.nisum.model.Product;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class ProductInfoServlet extends HttpServlet {
    private final ProductDAO productDAO = new ProductDAO();

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        try {
            String idParam = req.getParameter("id");
            if (idParam == null || idParam.isEmpty()) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Product ID is missing.");
                return;
            }

            int productId = Integer.parseInt(idParam);
            Product product = productDAO.getProductDetailsById(productId);

            if (product == null) {
                res.sendError(HttpServletResponse.SC_NOT_FOUND, "Product not found.");
                return;
            }

            req.setAttribute("product", product);
            req.getRequestDispatcher("/jsp/productInfo.jsp").forward(req, res);

        } catch (NumberFormatException e) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid product ID.");
        } catch (SQLException e) {
            throw new ServletException("Cannot fetch product details", e);
        }
    }
}
