<?php

namespace App\Exceptions;

use Illuminate\Http\JsonResponse;
use RuntimeException;

class InsufficientStockException extends RuntimeException
{
    public function __construct(
        public readonly int $branchId,
        public readonly int $productId,
        public readonly float $available,
        public readonly float $requested,
        ?string $message = null,
    ) {
        parent::__construct(
            $message ?? "Insufficient stock for product #{$productId} at branch #{$branchId} (available {$available}, requested {$requested}).",
        );
    }

    /**
     * Render as an HTTP 422 with a structured payload.
     */
    public function render(): JsonResponse
    {
        return response()->json([
            'message' => $this->getMessage(),
            'error' => 'insufficient_stock',
            'context' => [
                'branch_id' => $this->branchId,
                'product_id' => $this->productId,
                'available' => $this->available,
                'requested' => $this->requested,
            ],
        ], 422);
    }
}
