package dev.dao;

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

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_id, quantity, item_price) VALUES (?,?,?,?)";

        try {
            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            st.setInt(1, detail.getOrderId());
            st.setInt(2, detail.getMenuItemId());
            st.setInt(3, detail.getQuantity());
            st.setDouble(4, detail.getPrice());
            st.executeUpdate();

            st.close();
        } catch (SQLException e) {
            System.err.println("Error writing order details: " + e.getMessage());
        }

    }

    public List<OrderDetail> findByOrderId(int orderId) {

        List<OrderDetail> result = new ArrayList<>();

        String sql = "SELECT * FROM order_details WHERE order_id=?";

        try {

            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            st.setInt(1,orderId);

            ResultSet rs = st.executeQuery();
            while (rs.next()){
                result.add(new OrderDetail(
                                rs.getInt("id"),
                                rs.getInt("order_id"),
                                rs.getInt("menu_id"),
                                rs.getInt("quantity"),
                                rs.getDouble("item_price")
                        )
                );
            }

            st.close();

        } catch (SQLException e) {
            System.err.println("Error retrieving order details: " + e.getMessage());
        }

        return result;
        
    }

}