package dev.dao;

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

import java.math.BigDecimal;
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_details (order_id, menu_item_id, quantity, unit_price) VALUES (?, ?, ?, ?)";

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

            stmt.setInt(1, detail.getOrderId());
            stmt.setInt(2, detail.getMenuItemId());
            stmt.setInt(3, detail.getQuantity());
            stmt.setBigDecimal(4, detail.getPrice());

            stmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<OrderDetail> findByOrderId(int orderId) {

        // TODO:
        // Retrieve order details
        List<OrderDetail> details = new ArrayList<>();
        String sql = "SELECT id, order_id, menu_item_id, quantity, unit_price FROM order_details WHERE order_id = ?";

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

            stmt.setInt(1, orderId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    int oId = rs.getInt("order_id");
                    int menuItemId = rs.getInt("menu_item_id");
                    int quantity = rs.getInt("quantity");
                    BigDecimal price = rs.getBigDecimal("unit_price");

                    details.add(new OrderDetail(id, oId, menuItemId, quantity, price));
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return details;
    }

}