package dev.service;

import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OrderService {

    private final OrderDao orderDao = new OrderDao();
    private final MenuItemDao menuItemDao = new MenuItemDao();

    public void placeOrder(int userId, Map<Integer, Integer> cart) {
        Order order = new Order();
        order.setUserId(userId);
        order.setCreatedAt(LocalDateTime.now());

        double total = 0;
        List<OrderDetail> details = new ArrayList<>();

        for (Map.Entry<Integer, Integer> entry : cart.entrySet()) {
            MenuItem item = menuItemDao.getById(entry.getKey());
            if (item != null) {
                OrderDetail detail = new OrderDetail();
                detail.setMenuItemId(item.getId());
                detail.setQuantity(entry.getValue());
                detail.setPrice(item.getPrice());

                details.add(detail);
                total += item.getPrice() * entry.getValue();
            }
        }

        order.setTotalPrice(total);
        int orderId = orderDao.saveOrder(order, details);

        System.out.println("\nOrder saved successfully!");
        printReceipt(orderId);
    }

    public void printReceipt(int orderId) {
        Order order = orderDao.getOrderById(orderId);
        List<OrderDetail> details = orderDao.getOrderDetails(orderId);

        System.out.println("\n[Order Summary / Receipt]");
        System.out.println("---------------------------------------");
        System.out.printf("%-15s %-5s %-10s %-10s%n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");

        for (OrderDetail detail : details) {
            MenuItem item = menuItemDao.getById(detail.getMenuItemId());
            double subtotal = detail.getQuantity() * detail.getPrice();
            System.out.printf("%-15s %-5d $%-9.2f $%.2f%n", item.getName(), detail.getQuantity(), detail.getPrice(), subtotal);
        }

        System.out.println("---------------------------------------");
        System.out.printf("Final Total: $%.2f%n", order.getTotalPrice());
    }

    public void showOrderHistory(int userId) {
        List<Order> orders = orderDao.getOrdersByUserId(userId);

        System.out.println("\n[Order History]");
        if (orders.isEmpty()) {
            System.out.println("You have no past orders.");
            return;
        }

        for (Order order : orders) {
            System.out.printf("Order ID: %d | Date: %s | Total Spent: $%.2f%n",
                    order.getId(), order.getCreatedAt(), order.getTotalPrice());
        }
    }
}