<?php

namespace Database\Factories;

use App\Enums\CustomerType;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Models\DeliveryArea;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class OrderFactory extends Factory
{
    public function definition(): array
    {
        $deliveryArea = DeliveryArea::inRandomOrder()->first();
        $deliveryCost = $deliveryArea?->cost ?? 5000;
        $subtotal     = fake()->randomElement([30000, 45000, 62000, 80000, 95000, 120000]);
        $grandTotal   = $subtotal + $deliveryCost;
        $method       = fake()->randomElement(PaymentMethod::cases());

        return [
            'order_number'     => 'TBB-' . now()->format('Ymd') . '-' . fake()->unique()->numerify('####'),
            'customer_type'    => CustomerType::User->value,
            'user_id'          => User::role('customer')->inRandomOrder()->first()?->id,
            'guest_customer_id'=> null,
            'customer_name'    => fake()->name(),
            'customer_phone'   => '08' . fake()->numerify('#########'),
            'delivery_address_snapshot' => 'RT ' . fake()->numberBetween(1, 10) . '/RW ' . fake()->numberBetween(1, 5) . ' Desa Budiharja, ' . fake()->streetName(),
            'assigned_admin_id'=> null,
            'delivery_area_id' => $deliveryArea?->id,
            'delivery_cost'    => $deliveryCost,
            'voucher_id'       => null,
            'discount_amount'  => 0,
            'subtotal'         => $subtotal,
            'grand_total'      => $grandTotal,
            'status'           => OrderStatus::Pending->value,
            'payment_method'   => $method->value,
            'customer_notes'   => fake()->optional(0.3)->sentence(),
            'admin_notes'      => null,
            'payment_deadline' => $method->requiresProof() ? now()->addHours(24) : null,
        ];
    }

    public function pending(): static
    {
        return $this->state(fn () => ['status' => OrderStatus::Pending->value]);
    }

    public function paid(): static
    {
        return $this->state(fn () => ['status' => OrderStatus::Paid->value]);
    }

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

    public function cancelled(): static
    {
        return $this->state(fn () => ['status' => OrderStatus::Cancelled->value]);
    }

    public function cod(): static
    {
        return $this->state(fn () => [
            'payment_method'   => PaymentMethod::Cod->value,
            'payment_deadline' => null,
        ]);
    }

    public function guest(): static
    {
        return $this->state(fn () => [
            'customer_type' => CustomerType::Guest->value,
            'user_id'       => null,
        ]);
    }
}
