<?php

namespace Database\Factories;

use App\Enums\OrderChannel;
use App\Enums\OrderStatus;
use App\Enums\PriceType;
use App\Models\Customer;
use App\Models\Order;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends Factory<Order>
 */
class OrderFactory extends Factory
{
    public function definition(): array
    {
        $channel = fake()->randomElement(OrderChannel::cases());

        $defaultPriceType = match ($channel) {
            OrderChannel::SHOPEE => PriceType::SHOPEE,
            OrderChannel::TIKTOK => PriceType::TIKTOK,
            default => null,
        };

        $priceType = $defaultPriceType ?? fake()->randomElement(PriceType::cases());
        $subtotal = fake()->numberBetween(100_000, 5_000_000);
        $discount = fake()->numberBetween(0, (int) ($subtotal * 0.15));

        return [
            'customer_id' => Customer::factory(),
            'order_number' => 'ORD-'.now()->format('Ymd').'-'.Str::upper(Str::random(6)),
            'channel' => $channel->value,
            'price_type' => $priceType->value,
            'status' => OrderStatus::PENDING->value,
            'subtotal' => $subtotal,
            'discount' => $discount,
            'total_amount' => $subtotal - $discount,
            'notes' => fake()->optional()->sentence(),
            'cash_transaction_id' => null,
            'created_by_id' => User::factory(),
        ];
    }

    public function completed(): static
    {
        return $this->state(fn (array $attributes) => [
            'status' => OrderStatus::COMPLETED->value,
        ]);
    }
}
