<?php

namespace App\Http\Controllers;

use App\Events\ShipmentCreated;
use App\Events\ShipmentCreationFailed;
use App\Models\Order;
use App\Services\CourierService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ShippingController extends Controller
{
    public function __construct(protected CourierService $courierService)
    {
    }

    /**
     * Create shipment and call courier API
     * 
     * POST /orders/{id}/ship
     * POST /custom-orders/{id}/ship
     */
    public function createShipment(Request $request, Order $order)
    {
        try {
            $result = $this->courierService->createShipmentForOrder($order);

            // Emit event to trigger Slack notification and Trello updates
            ShipmentCreated::dispatch(
                $order,
                $result['waybill_id'],
                $result['tracking_number'],
                $result['sticker_path'],
                $result['waybill_path'],
            );

            return response()->json([
                'success' => true,
                'message' => 'Shipment created successfully',
                'shipment' => [
                    'waybill_id' => $result['waybill_id'],
                    'tracking_number' => $result['tracking_number'],
                    'sticker' => $result['sticker_path'] ? route('storage.file', $result['sticker_path']) : null,
                    'waybill' => $result['waybill_path'] ? route('storage.file', $result['waybill_path']) : null,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Shipment creation failed', [
                'order_uuid' => $order->uuid,
                'error' => $e->getMessage(),
            ]);

            // Emit failure event
            ShipmentCreationFailed::dispatch($order, $e->getMessage());

            return response()->json([
                'error' => 'Failed to create shipment',
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Retry shipment creation after previous failure
     * 
     * POST /admin/orders/{id}/retry-shipment
     */
    public function retryShipment(Request $request, Order $order)
    {
        // Verify order exists and has not already been successfully shipped
        if ($order->courier_waybill_id) {
            return response()->json([
                'error' => 'Order already has a valid shipment',
                'waybill_id' => $order->courier_waybill_id,
            ], 409);
        }

        // Re-run the shipment creation
        return $this->createShipment($request, $order);
    }
}
