<?php

namespace App\Services\Meta;

use InvalidArgumentException;

/** One ad creative: an image or a video, a destination, and the words around it. */
readonly class CreativeSpec
{
    /**
     * @param  string|null  $imageHash  the hash Meta returned for an uploaded image
     * @param  string|null  $videoId  the id Meta returned for an uploaded video
     * @param  string|null  $thumbnailUrl  a still from the video, which Meta requires
     */
    public function __construct(
        public string $adAccountId,
        public string $pageId,
        public string $landingUrl,
        public string $headline,
        public string $primaryText,
        public string $callToAction,
        public string $name,
        public ?string $imageHash = null,
        public ?string $videoId = null,
        public ?string $thumbnailUrl = null,
        /**
         * The video's cover, already uploaded, as a hash.
         *
         * Separate from imageHash, which means "this creative is an image ad"
         * and is what the one-or-the-other check below reads. A video has both
         * a video id and a cover, and conflating the two would make every video
         * look like an image to that check.
         *
         * Only the MCP needs it: ads_create_creative refuses a video with no
         * image_hash or image_url, and rejects the signed thumbnail URL Meta
         * itself hands back. Graph takes the URL happily, which is why this
         * stayed unnoticed while video went over Graph.
         */
        public ?string $thumbnailHash = null,
        public string $description = '',
        public ?string $instagramUserId = null,
    ) {
        // A creative is one thing or the other. Neither meant a null image hash
        // reached Meta as the word "null"; both would be ambiguous. Refusing
        // here keeps the failure at the point the mistake was made rather than
        // after a campaign and ad set already exist on the account.
        if (blank($imageHash) === blank($videoId)) {
            throw new InvalidArgumentException(
                'An ad creative needs exactly one of an image hash or a video id.'
            );
        }

        if (filled($videoId) && blank($thumbnailUrl)) {
            throw new InvalidArgumentException(
                'A video creative needs a thumbnail. Meta refuses video_data without one.'
            );
        }
    }

    public function isVideo(): bool
    {
        return filled($this->videoId);
    }

    /**
     * The Graph API shape.
     *
     * Video is not a variation on the image payload, it is a different one.
     * Meta names the headline title inside video_data, and the destination
     * sits on the call to action because video_data has no link field.
     *
     * The headline and description stay on the link or the video. Putting them
     * on the call to action (link_title, link_description) is what Ads Manager
     * now refuses, and it blocks Feed, Stories, Reels and the other placements.
     *
     * @return array<string, mixed>
     */
    public function storySpec(): array
    {
        return [
            'page_id' => $this->pageId,
            $this->isVideo() ? 'video_data' : 'link_data' => $this->isVideo()
                ? $this->videoData()
                : $this->linkData(),
        ];
    }

    /** @return array<string, mixed> */
    private function linkData(): array
    {
        return [
            'image_hash' => $this->imageHash,
            'link' => $this->landingUrl,
            'message' => $this->primaryText,
            'name' => $this->headline,
            'description' => $this->description,
            'call_to_action' => $this->callToActionValue(),
        ];
    }

    /** @return array<string, mixed> */
    private function videoData(): array
    {
        return array_filter([
            'video_id' => $this->videoId,
            'image_url' => $this->thumbnailUrl,
            'message' => $this->primaryText,
            'title' => $this->headline,
            'description' => $this->description,
            'call_to_action' => $this->callToActionValue(),
        ], fn (mixed $value): bool => $value !== '' && $value !== null);
    }

    /**
     * The button, and only the button.
     *
     * link_title and link_description on this value are deprecated. Meta will
     * not deliver the ad to Feed, Stories, Reels, Marketplace or search results
     * while they are set. The words belong on link_data or video_data.
     *
     * @return array{type: string, value: array{link: string}}
     */
    private function callToActionValue(): array
    {
        return [
            'type' => $this->callToAction,
            'value' => ['link' => $this->landingUrl],
        ];
    }

    /**
     * The MCP shape.
     *
     * ads_create_creative does not accept object_story_spec. Sending it is
     * refused before a creative exists, with JSON-RPC -32602. Headline and
     * description are arguments the tool does accept, so the copy goes there.
     * Graph still builds object_story_spec itself and keeps those words off
     * the button.
     *
     * @return array<string, mixed>
     */
    public function mcpArguments(): array
    {
        return array_filter([
            'ad_account_id' => ltrim(str_replace('act_', '', $this->adAccountId), '_'),
            'page_id' => $this->pageId,
            // image_hash carries two different things, which is Meta's choice
            // rather than ours: for an image ad it is the ad, for a video ad it
            // is the cover. There is no thumbnail_url parameter on
            // ads_create_creative at all, so sending one was sending nothing.
            //
            // Measured on 1 Oct: no cover is refused outright with "At least one
            // of image_hash or image_url must be provided", and the signed
            // scontent URL Meta returns for its own thumbnail is refused as a
            // bad image. A hash is the only form that works.
            'image_hash' => $this->imageHash ?? $this->thumbnailHash,
            'video_id' => $this->videoId,
            'link_url' => $this->landingUrl,
            'message' => $this->primaryText,
            'headline' => $this->headline,
            'description' => $this->description !== '' ? $this->description : null,
            'call_to_action_type' => $this->callToAction,
            'name' => $this->name,
            ...$this->instagramFields(),
        ], fn (mixed $value): bool => $value !== null);
    }

    /**
     * Who the ad appears as on Instagram.
     *
     * Sits beside object_story_spec rather than inside it, which is why it is
     * returned separately. Omitted entirely when there is no account, because
     * Meta reads a null as an explicit unset and rejects it.
     *
     * @return array<string, string>
     */
    public function instagramFields(): array
    {
        return $this->instagramUserId ? ['instagram_user_id' => $this->instagramUserId] : [];
    }
}
