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.time.format.DateTimeFormatter;
import java.util.List;

public class OrderService {

    private final OrderDao orderDao;
    private final OrderDetailDao orderDetailDao;
    private final MenuItemDao menuItemDao;

    public OrderService() {
        this.orderDao = new OrderDao();
        this.orderDetailDao = new OrderDetailDao();
        this.menuItemDao = new MenuItemDao();
    }

    public int placeOrder(int userId, List<OrderDetail> cart) {

        if (cart == null || cart.isEmpty()) {
            System.out.println("cart is empty");
            return -1;
        }

        double totalPrice = 0;
        for (OrderDetail o : cart) {
            MenuItem item = menuItemDao.findById((o.getMenuItemId()));
            if (item == null) {
                System.out.println("menu item with id " + o.getMenuItemId() + "not found");
                return -1;
            }
            o.setPrice(item.getPrice());
            totalPrice += item.getPrice() * o.getQuantity();
        }

        Order order = new Order();
        order.setUserId(userId);
        order.setTotalPrice(totalPrice);

        int orderId = orderDao.save(order);
        if (orderId == -1) {
            System.out.println("failed to save order.");
            return -1;
        }

        for (OrderDetail detail : cart) {
            detail.setOrderId(orderId);
            orderDetailDao.save(detail);
        }

        System.out.println("Order saved successfully!");
        return orderId;

    }

    public void printReceipt(int orderId) {

        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        if (details.isEmpty()) {
            System.out.println("order not found.");
            return;
        }

        double total = 0;

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

        for (OrderDetail detail : details) {
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            String itemName = (item != null) ? item.getName() : "Unknown";
            double subtotal = detail.getPrice() * detail.getQuantity();
            total += subtotal;

            System.out.printf("%-12s %-6d $%-7.2f $%-9.2f%n",
                    itemName,
                    detail.getQuantity(),
                    detail.getPrice(),
                    subtotal);
        }

        System.out.println("---------------------------------------");
        System.out.printf("%-12s %-6s %-8s $%-9.2f%n", "", "", "Final Total:", total);
        System.out.println("---------------------------------------");
    }

    public void showOrderHistory(int userId) {

        List<Order> orders = orderDao.findByUserId(userId);
        if (orders.isEmpty())
        {
            System.out.println("you have no orders.");
            return;
        }

        System.out.println("\nYour Order History:");
        System.out.println("--------------------------------------------------");
        System.out.printf("%-10s %-25s %-15s%n", "Order ID", "Date", "Total");
        System.out.println("--------------------------------------------------");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        for (Order order : orders) {
            System.out.printf("%-10d %-25s $%-14.2f%n",
                    order.getId(),
                    order.getCreatedAt().format(formatter),
                    order.getTotalPrice());
        }
        System.out.println("--------------------------------------------------");
    }
}

