<?php

declare(strict_types=1);

namespace App\Support\ProductTelemetry;

use InvalidArgumentException;

final class ProductUsageEventCatalog
{
    public const string ONBOARDING_CHECKPOINT_COMPLETED = 'product.onboarding.checkpoint_completed';

    public const string SUPPORT_DIAGNOSTICS_OPENED = 'product.support_diagnostics.opened';

    public const string OPERATIONS_STARTED = 'product.operations.started';

    public const string STORED_REPORT_CREATED = 'product.stored_report.created';

    public const string REVIEW_PACK_REQUESTED = 'product.review_pack.requested';

    private const DEFINITIONS = [
        self::ONBOARDING_CHECKPOINT_COMPLETED => [
            'feature_area' => 'onboarding',
            'label' => 'Onboarding checkpoints',
            'metadata_keys' => ['checkpoint_key', 'lifecycle_state', 'completed_at'],
        ],
        self::SUPPORT_DIAGNOSTICS_OPENED => [
            'feature_area' => 'support_diagnostics',
            'label' => 'Support diagnostics',
            'metadata_keys' => ['source_surface', 'operation_type'],
        ],
        self::OPERATIONS_STARTED => [
            'feature_area' => 'operations',
            'label' => 'Operations started',
            'metadata_keys' => ['operation_type'],
        ],
        self::STORED_REPORT_CREATED => [
            'feature_area' => 'stored_reports',
            'label' => 'Stored reports',
            'metadata_keys' => ['report_type'],
        ],
        self::REVIEW_PACK_REQUESTED => [
            'feature_area' => 'review_pack',
            'label' => 'Review packs requested',
            'metadata_keys' => ['source_surface', 'include_operations', 'include_pii'],
        ],
    ];

    /**
     * @return list<string>
     */
    public function names(): array
    {
        return array_keys(self::DEFINITIONS);
    }

    /**
     * @return array{feature_area: string, label: string, metadata_keys: list<string>}
     */
    public function definition(string $eventName): array
    {
        $definition = self::DEFINITIONS[$eventName] ?? null;

        if (! is_array($definition)) {
            throw new InvalidArgumentException("Unknown product telemetry event [{$eventName}].");
        }

        return $definition;
    }

    public function featureArea(string $eventName): string
    {
        return $this->definition($eventName)['feature_area'];
    }

    public function label(string $eventName): string
    {
        return $this->definition($eventName)['label'];
    }

    /**
     * @return list<string>
     */
    public function allowedMetadataKeys(string $eventName): array
    {
        return $this->definition($eventName)['metadata_keys'];
    }

    /**
     * @return array<string, string>
     */
    public function visibleFamilies(): array
    {
        $families = [];

        foreach ($this->names() as $eventName) {
            $families[$eventName] = $this->label($eventName);
        }

        return $families;
    }
}
