<?php

namespace Acms\Services\Embed;

/**
 * 埋め込み対象 URL から取得したメタ情報。
 *
 * 呼び出し側（ユニット・ブロックエディタ）が保存先の形を選べるよう、
 * 取得結果そのものだけを持つ不変オブジェクトにしている。
 */
class EmbedData
{
    private string $providerName;

    private string $authorName;

    private string $title;

    private string $description;

    private string $image;

    private string $html;

    public function __construct(
        string $providerName = '',
        string $authorName = '',
        string $title = '',
        string $description = '',
        string $image = '',
        string $html = ''
    ) {
        $this->providerName = $providerName;
        $this->authorName = $authorName;
        $this->title = $title;
        $this->description = $description;
        $this->image = $image;
        $this->html = $html;
    }

    public function getProviderName(): string
    {
        return $this->providerName;
    }

    public function getAuthorName(): string
    {
        return $this->authorName;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function getDescription(): string
    {
        return $this->description;
    }

    public function getImage(): string
    {
        return $this->image;
    }

    /**
     * oEmbed 等で得られた埋め込み HTML。Hook で差し替えられた場合もここに入る。
     */
    public function getHtml(): string
    {
        return $this->html;
    }

    /**
     * キャッシュへ保存できる連想配列へ変換する
     *
     * @return array{providerName: string, authorName: string, title: string, description: string, image: string, html: string}
     */
    public function toArray(): array
    {
        return [
            'providerName' => $this->providerName,
            'authorName' => $this->authorName,
            'title' => $this->title,
            'description' => $this->description,
            'image' => $this->image,
            'html' => $this->html,
        ];
    }

    /**
     * fromArray で復元する
     *
     * @param array<string, mixed> $data
     */
    public static function fromArray(array $data): self
    {
        return new self(
            isset($data['providerName']) ? (string) $data['providerName'] : '',
            isset($data['authorName']) ? (string) $data['authorName'] : '',
            isset($data['title']) ? (string) $data['title'] : '',
            isset($data['description']) ? (string) $data['description'] : '',
            isset($data['image']) ? (string) $data['image'] : '',
            isset($data['html']) ? (string) $data['html'] : ''
        );
    }
}
