<?php

namespace App\Campaigns\Manager;

/**
 * One object inside a campaign as the platform reported it, in its own words.
 *
 * Types are the platform's: a Meta ad set, a Google ad group or asset group, a
 * LinkedIn campaign group. They are not flattened into a common "ad set",
 * because that would make a Performance Max campaign look like it has ad sets
 * and a LinkedIn group look like a child of its own campaign.
 */
final readonly class PlatformEntity
{
    /**
     * @param  array<string, mixed>  $settings  normalized, credential-free, and
     *                                          never sent back to the platform
     */
    public function __construct(
        public string $type,
        public string $externalId,
        public ?string $parentType = null,
        public ?string $parentExternalId = null,
        public ?string $name = null,
        public ?string $status = null,
        public ?string $effectiveStatus = null,
        public array $settings = [],
    ) {}

    public function key(): string
    {
        return $this->type.'|'.$this->externalId;
    }

    /**
     * Everything a change can be detected in, in a stable order.
     *
     * @return array<string, mixed>
     */
    public function comparable(): array
    {
        return [
            'name' => $this->name,
            'status' => $this->status,
            'effective_status' => $this->effectiveStatus,
            'parent' => $this->parentExternalId,
            'settings' => Canonical::sort($this->settings),
        ];
    }

    public function fingerprint(): string
    {
        return hash('sha256', json_encode($this->comparable(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION));
    }
}
