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) " +
                "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.setDouble(4, detail.getPrice());

            stmt.executeUpdate();

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

    public List<OrderDetail> findByOrderId(int orderId) {

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

        String sql = "SELECT id, order_id, menu_item_id, quantity, price " +
                "FROM order_details WHERE order_id = ? ORDER BY id";

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

            stmt.setInt(1, orderId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    details.add(new OrderDetail(
                            rs.getInt("id"),
                            rs.getInt("order_id"),
                            rs.getInt("menu_item_id"),
                            rs.getInt("quantity"),
                            rs.getDouble("price")
                    ));
                }
            }

        } catch (SQLException e) {
            System.out.println("Error while loading order details: " + e.getMessage());
        }

        return details;
    }

}
