<?php

declare(strict_types=1);

namespace Cone\Bazar\Database\Factories;

use Cone\Bazar\Bazar;
use Cone\Bazar\Models\Order;
use Cone\Bazar\Models\Transaction;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @template TModel of \Illuminate\Database\Eloquent\Model
 */
class OrderFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var class-string<\Illuminate\Database\Eloquent\Model>
     */
    protected $model = Order::class;

    /**
     * Get the name of the model that is generated by the factory.
     *
     * @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
     */
    public function modelName(): string
    {
        return $this->model::getProxiedClass();
    }

    /**
     * Define the model's default state.
     */
    public function definition(): array
    {
        return [
            'discount' => 0,
            'currency' => Bazar::getCurrency(),
        ];
    }

    /**
     * Configure the model factory.
     */
    public function configure(): static
    {
        return $this->afterCreating(function (Order $order): void {
            $order->transactions->each(function (Transaction $transaction) use ($order): void {
                $transaction->order()->associate($order)->save();
            });
        });
    }

    /**
     * Configure the paid state.
     */
    public function paid(): static
    {
        return $this->afterMaking(function (Order $order): void {
            $order->transactions->push(
                (Transaction::proxy())::factory()->completed()->make(['amount' => $order->getTotalPayable()])
            );
        });
    }

    /**
     * Configure the refunded state.
     */
    public function refunded(): static
    {
        return $this->paid()->afterMaking(function (Order $order): void {
            $order->transactions->push(
                (Transaction::proxy())::factory()->refund()->completed()->make(['amount' => $order->getTotalPayable()])
            );
        });
    }
}
