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

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, detail.getOrderId());
            pstmt.setInt(2, detail.getMenuItemId());
            pstmt.setInt(3, detail.getQuantity());
            pstmt.setDouble(4, detail.getPriceAtPurchase());

            pstmt.executeUpdate();

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

    public List<OrderDetail> findByOrderId(int orderId) {

        List<OrderDetail> details = new ArrayList<>();
        String sql = "SELECT * FROM order_details WHERE order_id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, orderId);

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    OrderDetail detail = new OrderDetail(
                            rs.getInt("id"),
                            rs.getInt("order_id"),
                            rs.getInt("menu_item_id"),
                            rs.getInt("quantity"),
                            rs.getDouble("price_at_purchase")
                    );
                    details.add(detail);
                }
            }
        } catch (SQLException e) {
            System.err.println("Error retrieving order details: " + e.getMessage());
        }
        return details;
    }

}