<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\ProductUsageEvent;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Support\ProductTelemetry\ProductUsageEventCatalog;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends Factory<ProductUsageEvent>
 */
class ProductUsageEventFactory extends Factory
{
    protected $model = ProductUsageEvent::class;

    /**
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $catalog = new ProductUsageEventCatalog();
        $eventName = ProductUsageEventCatalog::ONBOARDING_CHECKPOINT_COMPLETED;

        return [
            'managed_environment_id' => ManagedEnvironment::factory()->for(Workspace::factory()),
            'workspace_id' => function (array $attributes): int {
                $tenantId = $attributes['managed_environment_id'] ?? null;

                if (! is_numeric($tenantId)) {
                    return (int) Workspace::factory()->create()->getKey();
                }

                $tenant = ManagedEnvironment::query()->whereKey((int) $tenantId)->first();

                if (! $tenant instanceof ManagedEnvironment || $tenant->workspace_id === null) {
                    return (int) Workspace::factory()->create()->getKey();
                }

                return (int) $tenant->workspace_id;
            },
            'user_id' => User::factory(),
            'event_name' => $eventName,
            'feature_area' => $catalog->featureArea($eventName),
            'subject_type' => 'managed_environment_onboarding_session',
            'subject_id' => (string) fake()->numberBetween(1, 999999),
            'metadata' => [
                'checkpoint_key' => 'tenant_connected',
                'lifecycle_state' => 'completed',
            ],
            'occurred_at' => now(),
        ];
    }

    /**
     * @param  array<string, mixed>  $metadata
     */
    public function forEvent(string $eventName, array $metadata = []): static
    {
        $catalog = new ProductUsageEventCatalog();

        return $this->state(fn (): array => [
            'event_name' => $eventName,
            'feature_area' => $catalog->featureArea($eventName),
            'metadata' => $metadata,
        ]);
    }
}
