package dev.dao;

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

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailDao {

    public void save(OrderDetail detail) {
        String query = "INSERT INTO orders_detail (order_id, item_id, quantity, item_price) VALUES (?, ?, ?, ?)";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setInt(1, detail.getOrderId());
            ps.setInt(2, detail.getMenuItemId());
            ps.setInt(3, detail.getQuantity());
            ps.setDouble(4, detail.getPrice());

            ps.executeUpdate();

        } catch (SQLException e) {
            System.err.println("Error saving order detail: " + e.getMessage());
        }
    }

    public List<OrderDetail> findByOrderId(int orderId) {
        String query = "SELECT od.uid, od.order_id, od.item_id, od.quantity, od.item_price, mi.name AS item_name " +
                "FROM orders_detail od " +
                "JOIN menu_item mi ON od.item_id = mi.uid " +
                "WHERE od.order_id = ? " +
                "ORDER BY od.uid";

        List<OrderDetail> details = new ArrayList<>();

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setInt(1, orderId);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                OrderDetail detail = new OrderDetail();
                detail.setId(rs.getInt("uid"));
                detail.setOrderId(rs.getInt("order_id"));
                detail.setMenuItemId(rs.getInt("item_id"));
                detail.setQuantity(rs.getInt("quantity"));
                detail.setPrice(rs.getDouble("item_price"));
                details.add(detail);
            }

            return details;

        } catch (SQLException e) {
            System.err.println("Error finding order details: " + e.getMessage());
            return new ArrayList<>();
        }
    }
}