package dev.dao;

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

import java.sql.*;
import java.time.LocalDateTime;
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_detail (order_id, menu_item_id,quantity, unit_price) VALUES (?, ?, ?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();) {
            PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setInt(1, detail.getOrderId());
            stmt.setInt(2, detail.getMenuItemId());
            stmt.setInt(3, detail.getQuantity());
            stmt.setDouble(4, detail.getPrice());
            stmt.executeUpdate();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    public List<OrderDetail> findByOrderId(int orderId) {

        // TODO:
        // Retrieve order details
        // Retrieve all orders of a user
        List<OrderDetail> orderDetails = new ArrayList<>();
        String sql = "SELECT * FROM order_detail 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 orderUserId = rs.getInt("order_id");
                   int menuItemId = rs.getInt("menu_item_id");
                   int quantity = rs.getInt("quantity");
                   double unitPrice = rs.getDouble("unit_price");
                   OrderDetail orderDetail = new OrderDetail(id, orderUserId, menuItemId, quantity, unitPrice);
                   orderDetails.add(orderDetail);
               }
           }
            return orderDetails;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}