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 connection = DatabaseConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {

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

            statement.executeUpdate();
        } catch (SQLException e) {
            System.out.println("Database Error: Unable to connect or execute query.");
        }
    }

    public List<OrderDetail> findByOrderId(int orderId) {
        List<OrderDetail> details = new ArrayList<>();
        String sql = "SELECT id, order_id, menu_item_id, quantity, price_at_purchase FROM order_details WHERE order_id = ?";

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

            statement.setInt(1, orderId);

            try (ResultSet rs = statement.executeQuery()) {
                while (rs.next()) {
                    OrderDetail detail = new OrderDetail();
                    detail.setId(rs.getInt("id"));
                    detail.setOrderId(rs.getInt("order_id"));
                    detail.setMenuItemId(rs.getInt("menu_item_id"));
                    detail.setQuantity(rs.getInt("quantity"));
                    detail.setPrice(rs.getDouble("price_at_purchase"));

                    details.add(detail);
                }
            }
        } catch (SQLException e) {
            System.out.println("Database Error: Unable to connect or execute query.");
        }
        return details;
    }
}