<?php

namespace Database\Factories;

use App\Enums\Status;
use App\Models\Product;
use App\Models\ProductVariant;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends Factory<ProductVariant>
 */
class ProductVariantFactory extends Factory
{
    public function definition(): array
    {
        return [
            'product_id' => Product::factory(),
            'color_id' => null,
            'size_id' => null,
            'sku' => 'VAR-'.Str::upper(Str::random(10)),
            'status' => Status::Active,
        ];
    }

    /**
     * Every variant needs an inventory row (the app's invariant — see
     * Step 2/8) so a bare ProductVariant::factory()->create() is never
     * left without one, even if a test doesn't care about stock levels.
     *
     * Deliberately never checks `$variant->inventory` (property access)
     * here — on a just-created model that always evaluates false, but
     * doing so caches the *null* relation result on this instance, and
     * that cache never refreshes even after the row is created below —
     * so callers reading ->inventory afterward see null despite the row
     * genuinely existing. Query through the relation method instead.
     */
    public function configure(): static
    {
        return $this->afterCreating(function (ProductVariant $variant) {
            $variant->inventory()->create(['quantity' => 10, 'low_stock_threshold' => 5]);
        });
    }

    public function withStock(int $quantity, int $threshold = 5): static
    {
        return $this->afterCreating(function (ProductVariant $variant) use ($quantity, $threshold) {
            $variant->inventory()->updateOrCreate([], ['quantity' => $quantity, 'low_stock_threshold' => $threshold]);
        });
    }
}
