package dev.service;

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

import java.util.*;

public class OrderService {

    private final MenuItemDao menuItemDao = new MenuItemDao();
    private final OrderDao orderDao = new OrderDao();
    private final OrderDetailDao orderDetailDao = new OrderDetailDao();
    private final Scanner scanner = new Scanner(System.in);

    public void placeOrder(int userId) {
        Map<Integer, Integer> cart = new HashMap<>(); // MenuItemID -> Quantity

        while (true) {
            System.out.print("Enter the ID of the item to add (or 0 to complete order): ");
            int itemId = scanner.nextInt();
            if (itemId == 0) {
                break;
            }

            MenuItem item = menuItemDao.findById(itemId);
            if (item == null) {
                System.out.println("Invalid Menu Item ID! Try again.");
                continue;
            }

            System.out.print("Enter quantity: ");
            int qty = scanner.nextInt();
            if (qty <= 0) {
                System.out.println("Quantity must be greater than zero!");
                continue;
            }

            cart.put(itemId, cart.getOrDefault(itemId, 0) + qty);
            System.out.println("Added " + qty + "x " + item.getName() + " to cart.");
        }

        if (cart.isEmpty()) {
            System.out.println("Cart is empty. Order cancelled.");
            return;
        }

        // Calculate Grand Total
        double grandTotal = 0;
        List<OrderDetail> details = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : cart.entrySet()) {
            MenuItem item = menuItemDao.findById(entry.getKey());
            double subTotal = item.getPrice() * entry.getValue();
            grandTotal += subTotal;

            OrderDetail detail = new OrderDetail();
            detail.setMenuItemId(item.getId());
            detail.setQuantity(entry.getValue());
            detail.setPrice(item.getPrice()); // Secure current purchase price
            details.add(detail);
        }

        // Persist Order
        Order order = new Order();
        order.setUserId(userId);
        order.setTotalPrice(grandTotal);
        int orderId = orderDao.save(order);

        if (orderId == -1) {
            System.out.println("An issue occurred. Order could not be created.");
            return;
        }

        // Persist Order Details
        for (OrderDetail detail : details) {
            detail.setOrderId(orderId);
            orderDetailDao.save(detail);
        }

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

    public void printReceipt(int orderId) {
        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        if (details == null || details.isEmpty()) {
            System.out.println("Receipt not found.");
            return;
        }

        System.out.println("\n=======================================");
        System.out.println("           🧾 ORDER RECEIPT            ");
        System.out.println("=======================================");
        System.out.printf("%-20s %-5s %-8s %-8s\n", "Item", "Qty", "Unit", "Total");
        System.out.println("-".repeat(43));

        double total = 0;
        for (OrderDetail detail : details) {
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            double lineTotal = detail.getPrice() * detail.getQuantity();
            total += lineTotal;
            System.out.printf("%-20s %-5d $%-7.2f $%-7.2f\n",
                    item.getName(), detail.getQuantity(), detail.getPrice(), lineTotal);
        }
        System.out.println("-".repeat(43));
        System.out.printf("Final Total:                           $%-7.2f\n", total);
        System.out.println("=======================================\n");
    }

    public void showOrderHistory(int userId) {
        List<Order> orders = orderDao.findByUserId(userId);
        if (orders == null || orders.isEmpty()) {
            System.out.println("No past orders found.");
            return;
        }

        System.out.println("\n=== PAST ORDERS ===");
        for (Order o : orders) {
            System.out.printf("Order #%d | Date: %s | Total Spent: $%.2f\n",
                    o.getId(), o.getCreatedAt().toString(), o.getTotalPrice());
        }
        System.out.println("===================\n");
    }
}