<?php

namespace App\Services\Meta;

/**
 * Primary text, headline, description, and URL from one Meta ad creative.
 *
 * Meta does not store those lines under those names. A plain creative keeps
 * them on the story spec. A dynamic creative leaves body and title empty and
 * keeps the words in the asset feed. The destination is a link on the story,
 * the call to action, the asset feed, or the creative itself.
 */
class AdCreativeCopy
{
    /**
     * @param  array<string, mixed>  $ad
     * @return array{name: string, status: string, effective_status: string, campaign_id: string, primary_text: string, headline: string, description: string, url: string}
     */
    public function fromAd(array $ad): array
    {
        $creative = is_array($ad['creative'] ?? null) ? $ad['creative'] : [];
        $story = is_array($creative['object_story_spec'] ?? null) ? $creative['object_story_spec'] : [];
        $link = is_array($story['link_data'] ?? null) ? $story['link_data'] : [];
        $video = is_array($story['video_data'] ?? null) ? $story['video_data'] : [];
        $template = is_array($story['template_data'] ?? null) ? $story['template_data'] : [];
        $feed = is_array($creative['asset_feed_spec'] ?? null) ? $creative['asset_feed_spec'] : [];

        return [
            'name' => trim((string) ($ad['name'] ?? '')),
            'status' => (string) ($ad['status'] ?? ''),
            'effective_status' => (string) ($ad['effective_status'] ?? ''),
            'campaign_id' => (string) ($ad['campaign_id'] ?? ''),
            'primary_text' => $this->line(
                $creative['body'] ?? null,
                $link['message'] ?? null,
                $video['message'] ?? null,
                $template['message'] ?? null,
                $feed['bodies'] ?? null,
            ),
            'headline' => $this->line(
                $creative['title'] ?? null,
                $link['name'] ?? null,
                $video['title'] ?? null,
                $template['name'] ?? null,
                $feed['titles'] ?? null,
            ),
            'description' => $this->line(
                $link['description'] ?? null,
                $video['link_description'] ?? null,
                $template['description'] ?? null,
                $feed['descriptions'] ?? null,
            ),
            'url' => $this->url($link, $video, $template, $feed, $creative),
        ];
    }

    /**
     * @param  array<string, mixed>  $link
     * @param  array<string, mixed>  $video
     * @param  array<string, mixed>  $template
     * @param  array<string, mixed>  $feed
     * @param  array<string, mixed>  $creative
     */
    private function url(array $link, array $video, array $template, array $feed, array $creative): string
    {
        foreach ([
            $link['link'] ?? null,
            data_get($link, 'call_to_action.value.link'),
            data_get($video, 'call_to_action.value.link'),
            $template['link'] ?? null,
            data_get($template, 'call_to_action.value.link'),
            $creative['link_url'] ?? null,
            $creative['object_url'] ?? null,
        ] as $candidate) {
            if (is_string($candidate) && trim($candidate) !== '') {
                return trim($candidate);
            }
        }

        foreach (is_array($feed['link_urls'] ?? null) ? $feed['link_urls'] : [] as $item) {
            $website = is_array($item) ? ($item['website_url'] ?? null) : null;

            if (is_string($website) && trim($website) !== '') {
                return trim($website);
            }
        }

        return '';
    }

    private function line(mixed ...$sources): string
    {
        foreach ($sources as $source) {
            $texts = $this->texts($source);

            if ($texts !== []) {
                return implode("\n", $texts);
            }
        }

        return '';
    }

    /**
     * @return list<string>
     */
    private function texts(mixed $value): array
    {
        if (is_string($value)) {
            $value = trim($value);

            return $value === '' ? [] : [$value];
        }

        if (! is_array($value)) {
            return [];
        }

        if (array_key_exists('text', $value) && is_string($value['text'])) {
            $text = trim($value['text']);

            return $text === '' ? [] : [$text];
        }

        $texts = [];

        foreach ($value as $item) {
            foreach ($this->texts($item) as $text) {
                if (! in_array($text, $texts, true)) {
                    $texts[] = $text;
                }
            }
        }

        return $texts;
    }
}
