<?php

namespace Database\Factories;

use App\Actions\OpenSubscription;
use App\Models\Customer;
use App\Models\Order;
use App\Models\Subscription;
use Illuminate\Database\Eloquent\Factories\Factory;

/** @extends Factory<Order> */
class OrderFactory extends Factory
{
    protected $model = Order::class;

    public function definition(): array
    {
        return [
            'customer_id' => Customer::factory(),
            'plan' => 'start',
            'amount_cents' => 1900,
            'currency' => 'EUR',
            'datacenter' => 'fsn',
            'status' => 'paid',
        ];
    }

    /**
     * A purchase that opened a contract — what a paid order looks like in
     * production, and what provisioning now requires. An unknown plan is left
     * without one on purpose, so the fail-closed path stays testable.
     */
    public function withSubscription(string $term = Subscription::TERM_MONTHLY): static
    {
        return $this->afterCreating(function (Order $order) use ($term) {
            if (Subscription::knowsPlan($order->plan)) {
                app(OpenSubscription::class)($order, $term);
            }
        });
    }
}
