<?php

namespace Database\Factories;

use App\Models\Customer;
use App\Models\EggPrice;
use App\Models\Order;
use Illuminate\Database\Eloquent\Factories\Factory;

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

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $date = $this->faker->dateTimeBetween('-3 months', 'now');

        $eggPrice = EggPrice::inRandomOrder()->first() ?? EggPrice::factory()->create();

        $customer = Customer::inRandomOrder()->first() ?? Customer::factory()->create();

        $eggQuantity = $this->faker->numberBetween(10, 500);
        $unitPrice = $eggPrice->price;
        $discount = $this->faker->optional(0.3)->numberBetween(5000, 50000) ?? 0;
        $subtotal = $eggQuantity * $unitPrice;
        $totalAmount = max(0, $subtotal - $discount);

        return [
            'customer_id' => $customer->id,
            'unit_id' => $eggPrice->unit_id,
            'egg_quantity' => $eggQuantity,
            'unit_price' => $unitPrice,
            'order_date' => $date,
            'status' => $this->faker->randomElement(['pending', 'completed', 'cancelled']),
            'discount' => $discount,
            'total_amount' => $totalAmount,
            'notes' => $this->faker->optional(0.4)->sentence(),
        ];
    }
}
