package com.nisum.dao;

import com.nisum.model.CartItem;
import com.nisum.model.ShoppingCart;
import com.nisum.util.DBConnection;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.sql.Statement;

public class CartDAO {

    public ShoppingCart getOrCreateCart(int userId) throws SQLException {
        String sql = "SELECT * FROM ShoppingCart WHERE UserID = ?";
        try (Connection conn = DBConnection.get();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return extractCart(rs);

            } else {
                // create cart
                String insert = "INSERT INTO ShoppingCart (UserID, CartTotal, CreatedDate, LastUpdatedDate) VALUES (?, 0.0, NOW(), NOW())";
                PreparedStatement ins = conn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
                ins.setInt(1, userId);
                ins.executeUpdate();
                ResultSet keys = ins.getGeneratedKeys();
                if (keys.next()) {
                    int cartId = keys.getInt(1);
                    return new ShoppingCart(cartId, userId, BigDecimal.ZERO, new Date(), new Date());
                }
            }
        }
        return null;
    }
    public void addToCart(int cartId, int productId, int quantity) throws SQLException {
        String selectSql = "SELECT SKU, DiscountPrice, Discount FROM ProductCategory WHERE ProductID = ?";
        String insertSql = "INSERT INTO CartItems (CartID, ProductID, SKU, Quantity, UnitPrice, Discount, FinalPrice, IsSavedForLater) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, 0) " +
                "ON DUPLICATE KEY UPDATE Quantity = Quantity + ?, FinalPrice = FinalPrice + ?";

        try (Connection conn = DBConnection.get();
             PreparedStatement selectStmt = conn.prepareStatement(selectSql)) {

            selectStmt.setInt(1, productId);
            try (ResultSet rs = selectStmt.executeQuery()) {
                if (!rs.next()) {
                    throw new SQLException("ProductCategory entry with ProductID " + productId + " not found.");
                }

                String sku = rs.getString("SKU");
                BigDecimal price = rs.getBigDecimal("DiscountPrice");
                BigDecimal discount = rs.getBigDecimal("Discount");
                BigDecimal finalPrice = price.multiply(BigDecimal.valueOf(quantity));

                try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
                    insertStmt.setInt(1, cartId);
                    insertStmt.setInt(2, productId);
                    insertStmt.setString(3, sku);
                    insertStmt.setInt(4, quantity);
                    insertStmt.setBigDecimal(5, price);
                    insertStmt.setBigDecimal(6, discount != null ? discount : BigDecimal.ZERO);
                    insertStmt.setBigDecimal(7, finalPrice);

                    // For ON DUPLICATE KEY UPDATE
                    insertStmt.setInt(8, quantity);
                    insertStmt.setBigDecimal(9, finalPrice);
                    System.out.println("insert parameters");
                    insertStmt.executeUpdate();
                }
            }
        }
    }


    public List<CartItem> getCartItems(int userId) throws SQLException {
        List<CartItem> list = new ArrayList<>();

        String sql = "SELECT ci.CartItemID, p.ProductName, p.imageurl as imageurl,  pa2.AttributeValue AS Color, " +
                "ci.Quantity AS CartQty, ci.UnitPrice, ci.Discount, ci.FinalPrice, " +
                "pi.Quantity AS StockQty, " +
                "CASE WHEN pi.Quantity >= ci.Quantity THEN 'In Stock' ELSE 'Out of Stock' END AS StockStatus, " +
                "pc.Discount AS DiscountPercent, sc.CartTotal " +
                "FROM ShoppingCart sc " +
                "JOIN CartItems ci ON sc.CartID = ci.CartID " +
                "JOIN Product p ON ci.ProductID = p.ProductID " +
                "LEFT JOIN ProductInventory pi ON ci.SKU = pi.SKU " +
                "LEFT JOIN ProductCategory pc ON p.ProductID = pc.ProductID AND ci.SKU = pc.SKU " +
                "LEFT JOIN ProductAttributes pa2 ON pa2.ProductID = p.ProductID AND pa2.AttributeName = 'Color' " +
                "WHERE sc.UserID = ?";

        try (Connection conn = DBConnection.get();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                CartItem item = new CartItem();
                item.setCartItemId(rs.getInt("CartItemID"));
                item.setProductName(rs.getString("ProductName"));
                item.setColor(rs.getString("Color"));
                item.setQuantity(rs.getInt("CartQty"));
                item.setUnitPrice(rs.getDouble("UnitPrice"));
                item.setDiscount(rs.getDouble("Discount"));
                item.setFinalPrice(rs.getDouble("FinalPrice"));
                item.setStockStatus(rs.getString("StockStatus"));
                item.setDiscountPercent(rs.getInt("DiscountPercent"));
                item.setImageurl(rs.getString("imageurl"));

                list.add(item);

                System.out.println(item);
            }
        }
        System.out.println(list);
        return list;
    }

    private ShoppingCart extractCart(ResultSet rs) throws SQLException {
        return new ShoppingCart(
                rs.getInt("CartID"),
                rs.getInt("UserID"),
                rs.getBigDecimal("CartTotal"),
                rs.getTimestamp("CreatedDate"),
                rs.getTimestamp("LastUpdatedDate")
        );
    }
}

