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) {

        // TODO:
        // Insert order detail

        String sql = "INSERT INTO order_detail (order_id, menu_item_id, quantity, price) VALUES(?, ?, ?, ?)";

        try(Connection connection = DatabaseConnection.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, detail.getOrderId());
            preparedStatement.setInt(2, detail.getMenuItemId());
            preparedStatement.setInt(3, detail.getQuantity());
            preparedStatement.setDouble(4, detail.getPrice());

            preparedStatement.executeQuery();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public List<OrderDetail> findByOrderId(int orderId) {

        // Retrieve order details

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

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

        try(Connection connection = DatabaseConnection.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, orderId);

            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {

                OrderDetail orderDetail = new OrderDetail();

                orderDetail.setId(resultSet.getInt("id"));
                orderDetail.setOrderId(resultSet.getInt("order_id"));
                orderDetail.setMenuItemId(resultSet.getInt("menu_item_id"));
                orderDetail.setQuantity(resultSet.getInt("quantity"));
                orderDetail.setPrice(resultSet.getDouble("price"));

                orderDetails.add(orderDetail);
            }



        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return orderDetails;
    }

}