package dev.dao;

import dev.database.DatabaseConnection;
import dev.model.OrderDetail;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailDao {

    public void save(OrderDetail detail) {

        String sql = "INSERT INTO order_details (order_id, menu_items_id, quantity, price_at_purchase) VALUES (?,?,?,?)";
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql))
        {
            stmt.setInt(2, detail.getOrderId());
            stmt.setInt(3, detail.getMenuItemId());
            stmt.setInt(4, detail.getQuantity());
            stmt.setDouble(5, detail.getPrice());

            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0)
            {
                throw new SQLException("unsuccessful");
            }


        } catch (SQLException e)
        {
            e.printStackTrace();
        }

    }

    public List<OrderDetail> findByOrderId(int orderId) {

        String sql = "SELECT id, order_id, menu_items_id, quantity, price_at_purchase FROM order_details WHERE order_id = ?";

        List<OrderDetail> orderDetails = new ArrayList<>();
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql))
        {

            stmt.setInt(1, orderId);
            try (ResultSet rs = stmt.executeQuery())
            {
                while (rs.next())
                {
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setId(rs.getInt("id"));
                    orderDetail.setOrderId(rs.getInt("order_id"));
                    orderDetail.setMenuItemId(rs.getInt("menu_item_id"));
                    orderDetail.setQuantity(rs.getInt("quantity"));
                    orderDetail.setPrice(rs.getDouble("price_at_purchase"));

                    orderDetails.add(orderDetail);
                }
            }

        } catch (SQLException e)
        {
            e.printStackTrace();
        }

        return orderDetails;
    }

}