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 stmt = DatabaseConnection.getConnection().prepareStatement(sql);
            stmt.setInt(1, detail.getOrderId());
            stmt.setInt(2, detail.getMenuItemId());
            stmt.setInt(3, detail.getQuantity());
            stmt.setDouble(4, detail.getPrice());
            stmt.executeUpdate();
        } 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 stmt = DatabaseConnection.getConnection().prepareStatement(sql);
            stmt.setInt(1,orderId);

            ResultSet rs = stmt.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")
                        )
                );
            }
        } catch (SQLException e) {
            System.err.println("Error retrieving order details: " + e.getMessage());
        }

        return result;
    }

}