<?php

namespace Database\Factories;

use App\Models\Feed;
use App\Models\FeedPurchase;
use App\Models\FeedPurchaseItem;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\FeedPurchase>
 */
class FeedPurchaseFactory extends Factory
{
    protected $model = FeedPurchase::class;

    public function definition(): array
    {
        $date = $this->faker->dateTimeBetween('-3 months', 'now');

        return [
            'reference_number' => $this->faker->unique()->numerify('PO-#####'),
            'purchase_date' => $date,
            'total_price' => 0, // akan dihitung ulang setelah items dibuat
            'notes' => $this->faker->optional(0.4)->sentence(),
        ];
    }

    public function configure()
    {
        return $this->afterCreating(function (FeedPurchase $purchase) {
            $feeds = Feed::inRandomOrder()->take(5)->get();

            if ($feeds->isEmpty()) {
                $feeds = Feed::factory()->count(5)->create();
            }

            $itemCount = $this->faker->numberBetween(1, min(5, $feeds->count()));
            $selectedFeeds = $feeds->shuffle()->take($itemCount);

            $total = 0;

            foreach ($selectedFeeds as $feed) {
                $quantity = $this->faker->numberBetween(1, 50);
                $unitPrice = $feed->price ?? $this->faker->numberBetween(10000, 150000);
                $subtotal = $quantity * $unitPrice;

                FeedPurchaseItem::create([
                    'feed_purchase_id' => $purchase->id,
                    'feed_id' => $feed->id,
                    'quantity' => $quantity,
                    'unit_price' => $unitPrice,
                    'subtotal' => $subtotal,
                ]);

                $total += $subtotal;
            }

            $purchase->update(['total_price' => $total]);

            // update stok feed sesuai logic di model
            $purchase->refresh();
            $purchase->updateFeedStock();
        });
    }
}
