<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\MailService;
use App\Services\RoyalMailService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ShipmentController extends Controller
{
    public function __construct(
        private RoyalMailService $royalMail,
        private MailService $mailService,
    ) {}

    /**
     * GET /admin/shipment/config
     * Returns whether Royal Mail is configured.
     */
    public function config(): JsonResponse
    {
        return response()->json([
            'configured' => $this->royalMail->isConfigured(),
            'services'   => RoyalMailService::services(),
        ]);
    }

    /**
     * POST /admin/orders/{id}/ship
     * Creates a Royal Mail shipment, stores tracking number, sets status to shipped.
     */
    public function ship(Request $request, int $id): JsonResponse
    {
        $request->validate([
            'service_code'  => 'required|string',
            'weight_grams'  => 'required|integer|min:1|max:30000',
        ]);

        $order = Order::with(['shippingAddress', 'user', 'items'])->findOrFail($id);

        if (in_array($order->status, ['shipped', 'delivered', 'cancelled', 'refunded'])) {
            return response()->json(['message' => 'Order cannot be shipped in its current status.'], 422);
        }

        $result = $this->royalMail->createShipment(
            $order,
            $request->service_code,
            $request->weight_grams
        );

        $order->update([
            'tracking_number' => $result['tracking_number'],
            'status'          => 'shipped',
        ]);

        $order->refresh()->load(['items', 'shippingAddress', 'user']);
        $this->mailService->sendOrderShipped($order);

        return response()->json([
            'tracking_number' => $result['tracking_number'],
            'label_url'       => $result['label_url'],
            'test_mode'       => $result['test_mode'],
            'message'         => $result['test_mode']
                ? 'Test mode: mock tracking number generated. Configure Royal Mail API to create real shipments.'
                : 'Shipment created successfully.',
        ]);
    }

    /**
     * GET /admin/orders/{id}/label
     * Returns the label PDF URL for an existing shipment.
     */
    public function label(int $id): JsonResponse
    {
        $order = Order::findOrFail($id);

        if (!$order->tracking_number) {
            return response()->json(['message' => 'No shipment found for this order.'], 404);
        }

        $url = $this->royalMail->getLabel($order->tracking_number);

        return response()->json([
            'label_url'       => $url,
            'tracking_number' => $order->tracking_number,
        ]);
    }
}
