<?php

namespace App\Http\Controllers\Api;

use App\Events\CancellationRequest;
use App\Events\CancelOrder;
use App\Http\Controllers\Controller;
use App\Services\OrderService;
use App\Traits\ApiResponse;

class OrderController extends Controller
{
    use ApiResponse;

    protected $orderService;

    public function __construct(OrderService $orderService)
    {
        $this->orderService = $orderService;
    }

    public function getOrderSync($orderId)
    {
        try {
            $data = $this->orderService->getOrderSync($orderId);

            return $this->successResponse($data);
        } catch(\Exception $e) {
            return $this->errorResponse(errorDetails: $e->getMessage());
        }
    }

    public function getOrders($customerId)
    {
        try {
            $data = $this->orderService->getOrders($customerId);

            return $this->successResponse($data);
        } catch(\Exception $e) {
            return $this->errorResponse(errorDetails: $e->getMessage());
        }
    }

    public function getOrderById($customerId, $orderId)
    {
        try {
            $data = $this->orderService->getOrderById($customerId, $orderId);
            return $this->successResponse($data);
        } catch(\Exception $e) {
            return $this->errorResponse(errorDetails: $e->getMessage());
        }
    }

    public function cancelOrder($customerId, $orderId)
    {
        try {
            $order = $this->orderService->cancelOrder($customerId, $orderId);
            
            broadcast(new CancelOrder($order))->toOthers();

            return $this->successResponse(null, 'Cancel order successfully');
        } catch(\Exception $e) {
            return $this->errorResponse('Failed to cancel order', 400, $e->getMessage());
        }
    }

    public function cancellationRequest($customerId, $orderId)
    {
        try {
            $order = $this->orderService->cancellationRequest($customerId, $orderId);
            
            broadcast(new CancellationRequest($order))->toOthers();

            return $this->successResponse(null, 'Cancellation order request successfully');
        } catch(\Exception $e) {
            return $this->errorResponse('Failed to cancellation order request', 400, $e->getMessage());
        }
    }
}
