package com.nisum.servlet;

import com.nisum.util.DBConnection;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDateTime;



public class UpdateQuantityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int cartItemId;
        try{
            cartItemId = Integer.parseInt(request.getParameter("cartItemId"));
        }
        catch (Exception e){
            cartItemId = 2;
        }
        int newQuantity = Integer.parseInt(request.getParameter("newQuantity"));
        String stockStatus = "in_stock";

        try (Connection con = DBConnection.get()) {

            // Step 1: Retrieve item details
            String selectSQL = "SELECT UnitPrice, Discount, CartID, SKU FROM CartItems WHERE CartItemID = ?";
            double unitPrice = 0, discount = 0;
            int cartId = 0;
            String sku = "";

            try (PreparedStatement ps = con.prepareStatement(selectSQL)) {
                ps.setInt(1, cartItemId);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    unitPrice = rs.getDouble("UnitPrice");
                    discount = rs.getDouble("Discount");
                    cartId = rs.getInt("CartID");
                    sku = rs.getString("SKU");
                } else {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            }

            // Step 2: Check inventory quantity (used only for response status)
            int stockQty = 0;
            try (PreparedStatement ps = con.prepareStatement("SELECT Quantity FROM ProductInventory WHERE SKU = ?")) {
                ps.setString(1, sku);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    stockQty = rs.getInt("Quantity");
                }
            }

            if (newQuantity > stockQty) {
                stockStatus = "out_of_stock";
            }

            // Step 3: Update CartItem
            double finalPrice = (unitPrice - discount) * newQuantity;
            try (PreparedStatement ps = con.prepareStatement(
                    "UPDATE CartItems SET Quantity = ?, FinalPrice = ? WHERE CartItemID = ?")) {
                ps.setInt(1, newQuantity);
                ps.setDouble(2, finalPrice);
                ps.setInt(3, cartItemId);
                ps.executeUpdate();
            }

            // Step 4: Recalculate and update ShoppingCart
            double newCartTotal = 0;
            try (PreparedStatement ps = con.prepareStatement(
                    "SELECT SUM(FinalPrice) AS Total FROM CartItems WHERE CartID = ?")) {
                ps.setInt(1, cartId);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    newCartTotal = rs.getDouble("Total");
                }
            }

            try (PreparedStatement ps = con.prepareStatement(
                    "UPDATE ShoppingCart SET CartTotal = ?, LastUpdatedDate = ? WHERE CartID = ?")) {
                ps.setDouble(1, newCartTotal);
                ps.setTimestamp(2, Timestamp.valueOf(LocalDateTime.now()));
                ps.setInt(3, cartId);
                ps.executeUpdate();
            }

            // Step 5: Respond with stock status
            response.setContentType("text/plain");
            response.getWriter().write(stockStatus);

        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
