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

        try (Connection c = DatabaseConnection.getConnection()) {

            double unitPrice = 0.0;

            String selectQuery = "SELECT * FROM menu_items";
            try (Statement stmt = c.createStatement();
                 ResultSet rs = stmt.executeQuery(selectQuery)) {

                while (rs.next()) {
                    int menuItemId = rs.getInt("id");
                    if (menuItemId == detail.getMenuItemId()) {
                        unitPrice = rs.getDouble("price");
                    }
                }
            }

            String insertQuery = "INSERT INTO order_details (order_id, menu_item_id, quantity, unit_price) VALUES (?, ?, ?, ?)";
            try (PreparedStatement pstmt = c.prepareStatement(insertQuery)) {
                pstmt.setInt(1, detail.getOrderId());
                pstmt.setInt(2, detail.getMenuItemId());
                pstmt.setInt(3, detail.getQuantity());
                pstmt.setDouble(4, unitPrice);
                pstmt.executeUpdate();
            }
        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }

    }

    public List<OrderDetail> findByOrderId(int orderId) {

        // TODO:
        // Retrieve order details

        List<OrderDetail> orderDetails = new ArrayList<>();
        try (Connection c = DatabaseConnection.getConnection()) {
            String selectQuery = "SELECT * FROM order_details";
            try (Statement stmt = c.createStatement();
                 ResultSet rs = stmt.executeQuery(selectQuery)) {

                while (rs.next()) {
                    int order_id = rs.getInt("order_id");
                    if (order_id == orderId) {
                        int id = rs.getInt("id");
                        int menu_item_id = rs.getInt("menu_item_id");
                        int quantity = rs.getInt("quantity");
                        double unit_price = rs.getDouble("unit_price");
                        OrderDetail orderDetail = new OrderDetail(id, order_id, menu_item_id, quantity, unit_price);
                        orderDetails.add(orderDetail);
                    }
                }
            }
        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }

        return orderDetails;
    }

}