<?php

namespace Database\Factories;

use App\Models\Customer;
use App\Models\Order;
use App\Models\Unit;
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 = $this->faker->numberBetween(28000, 35000);

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

        $eggQuantity = $this->faker->randomFloat(2, 10, 500);
        $unitPrice = $eggPrice / 10;
        $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' => Unit::inRandomOrder()->first()->id ?? Unit::factory()->create()->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(),
        ];
    }
}
