<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Enums\WarrantyType;
use App\Models\Asset;
use App\Models\AssetWarranty;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * Test data only.
 *
 * Unlike a real warranty, this factory writes `is_primary` directly rather
 * than going through WarrantyService — tests that exercise the invariant
 * (at most one primary per asset, renewal preserving history) call the
 * service themselves.
 *
 * @extends Factory<AssetWarranty>
 */
class AssetWarrantyFactory extends Factory
{
    public function definition(): array
    {
        $start = fake()->dateTimeBetween('-2 years', '-1 month');

        return [
            'asset_id' => Asset::factory(),
            'type' => fake()->randomElement(WarrantyType::cases()),
            'provider' => fake()->company(),
            'reference_number' => mb_strtoupper(fake()->bothify('WR-#####')),
            'start_date' => $start,
            'end_date' => (clone $start)->modify('+1 year'),
            'cost' => fake()->randomFloat(2, 2000, 25000),
            'is_primary' => false,
            'notes' => null,
        ];
    }

    public function primary(): static
    {
        return $this->state(fn (array $attributes): array => ['is_primary' => true]);
    }

    public function expiringInDays(int $days): static
    {
        return $this->state(fn (array $attributes): array => [
            'start_date' => now()->subYear(),
            'end_date' => now()->addDays($days),
        ]);
    }

    public function expired(): static
    {
        return $this->state(fn (array $attributes): array => [
            'start_date' => now()->subYears(2),
            'end_date' => now()->subMonth(),
        ]);
    }

    public function forAsset(Asset $asset): static
    {
        return $this->state(fn (array $attributes): array => ['asset_id' => $asset->getKey()]);
    }
}
