<?php

namespace Database\Factories;

use App\Models\ProductManagement\Category;
use App\Models\ProductManagement\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
 */
class ProductFactory extends Factory{

    protected $model = Product::class;

    public function definition(){
        $categories = Category::all()->pluck('id');

        return [
            'name'          => fake()->sentence(2, true),
            'slug'          => fake()->unique()->slug(2, true),
            'description'   => fake()->paragraph,
            'details'       => fake()->paragraph,
            'price'         => fake()->numberBetween(500, 30000),
            'category_id'   => $categories->random(),
            'featured'      => rand(0, 1),
            'active'        => true,
        ];
    }


    public function configure(){
      return  $this->afterCreating(function (Product $product){
            try {
                $images =  Storage::disk("assets")->allFiles("frontend/assets/products");

                if(filled($images)){
                    $images =  collect($images)->where( fn ($url) => !Str::contains($url,['alt',"detail"]));
                    $images = $images->map( fn ($url) => url($url))->toArray();
                    $images =  fake()->randomElements($images);
                    $product->uploadFiles($images);
                }

            }catch (\Exception $exception){
               echo $exception->getMessage()."\n";
            }
        });
    }
}
