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 DeleteItemServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Servlet called");
//        int  param =Integer.parseInt(request.getParameter("cartItemId"));
        System.out.println("Received POST request at: " + request.getRequestURI());
        System.out.println(request.getParameter("cartItemId"));
//        System.out.println("Received cartItemId param: " + param);
        int cartItemId;
        try{
            cartItemId = Integer.parseInt(request.getParameter("cartItemId"));
            System.out.println(cartItemId);
        }
        catch (Exception e){
            System.out.println("exception");
            cartItemId = 5;
            e.printStackTrace();
        }
        int cartId = -1;
        System.out.println("entering try");
        try (Connection con = DBConnection.get()) {
            System.out.println("connection done");
            // Step 1: Get the CartID of the item to delete
            String getCartIdSQL = "SELECT CartID FROM CartItems WHERE CartItemID = ?";
            try (PreparedStatement ps = con.prepareStatement(getCartIdSQL)) {
                ps.setInt(1, cartItemId);
                System.out.println("selected");
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    cartId = rs.getInt("CartID");
                } else {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            }

            // Step 2: Delete the CartItem
            String deleteSQL = "DELETE FROM CartItems WHERE CartItemID = ?";
            System.out.println(cartItemId);
            try (PreparedStatement ps = con.prepareStatement(deleteSQL)) {
                ps.setInt(1, cartItemId);
                System.out.println(cartItemId);
                int rowsAffected = ps.executeUpdate();
                if (rowsAffected == 0) {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    System.out.println("inside if");
                    return;
                }
            }

            // Step 3: Recalculate CartTotal
            double newCartTotal = 0.0;
            String sumSQL = "SELECT SUM(FinalPrice) AS Total FROM CartItems WHERE CartID = ?";
            System.out.println("calculate total price");
            try (PreparedStatement ps = con.prepareStatement(sumSQL)) {
                ps.setInt(1, cartId);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    newCartTotal = rs.getDouble("Total");
                }
            }

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

            // Step 5: Respond with success
            response.getWriter().write("deleted");

        } catch (SQLException e)
        {
            System.out.println("connection failed");
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
