<?php

namespace App\Campaigns\Manager\Editing\Writers;

use App\Campaigns\Manager\Editing\AdvancedEditFields;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityWriter;
use App\Models\Campaign;
use App\Models\CampaignPlatformEntity;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;

/**
 * Campaign name, status and budget, ad group name, status and CPC bid, and the
 * status of an ad or asset group. A status is written to that one object only:
 * pausing an ad never pauses its ad group.
 *
 * Every call goes out with an update mask naming only what changed, so nothing
 * else on the resource can be cleared by it. The budget is its own resource on
 * Google; a shared one is refused here as well as in the wizard, because
 * changing it would change every campaign that spends from it.
 *
 * A campaign rename and budget change are two calls. The budget goes first,
 * and if the rename then fails the editor reads back to report what landed.
 */
class GoogleEntityWriter implements EntityWriter
{
    /** @var array<string, list<string>> */
    private const array FIELDS = [
        'campaign' => ['name', 'status', 'daily_budget', 'bid_strategy', 'target_cpa', 'target_roas', 'start_time', 'end_time', ...AdvancedEditFields::GOOGLE, ...AdvancedEditFields::GOOGLE_SETTINGS],
        'ad_group' => ['name', 'status', 'cpc_bid', ...AdvancedEditFields::GOOGLE_GROUP],
        'ad' => ['status'],
        'asset_group' => ['status'],
    ];

    public function __construct(private readonly GoogleAdsService $google) {}

    public function write(Campaign $campaign, CampaignPlatformEntity $entity, array $patch, string $actor): void
    {
        $allowed = self::FIELDS[$entity->entity_type] ?? [];

        if ($patch === [] || array_diff(array_keys($patch), $allowed) !== []) {
            throw new EditRefused(sprintf('Only %s can be changed on a Google %s from here.', implode(', ', $allowed) ?: 'nothing', str_replace('_', ' ', $entity->entity_type)));
        }

        $connection = $this->connection($campaign);
        if (array_key_exists('conversion_goals', $patch)) {
            if (count($patch) !== 1) {
                throw new EditRefused('Review conversion goals separately.');
            }
            $this->google->updateManagerGoals($connection, $entity->external_id, $patch['conversion_goals'], (array) data_get($entity->settings, 'conversion_goals'));

            return;
        }

        $status = $patch['status'] ?? null;
        unset($patch['status']);

        if ($status !== null && ! in_array($status, ['ENABLED', 'PAUSED'], true)) {
            throw new EditRefused('Choose enabled or paused.');
        }

        // Settings first, so an object being switched on already carries them.
        if ($patch !== []) {
            $this->writeSettings($connection, $entity, $patch);
        }

        if ($status === null) {
            return;
        }

        if ($entity->entity_type === 'campaign') {
            $this->google->setLiveStatus($connection, ['campaign_id' => $entity->external_id], $status);

            return;
        }

        $this->google->setChildStatus(
            $connection,
            $entity->entity_type,
            $entity->external_id,
            $entity->entity_type === 'ad' ? $entity->parent_external_id : null,
            $status,
        );
    }

    /** @param  array<string, mixed>  $patch */
    private function writeSettings(GoogleAdsConnection $connection, CampaignPlatformEntity $entity, array $patch): void
    {
        if ($entity->entity_type === 'ad_group') {
            if (array_key_exists('keywords', $patch)) {
                $this->google->replaceAdGroupKeywords($connection, $entity->external_id, $patch['keywords']);
            }
            if (array_key_exists('audience_criteria', $patch)) {
                $this->google->updateManagerAudiences($connection, $entity->external_id, (array) data_get($entity->settings, 'manager_audience_criteria'), $patch['audience_criteria']);
            }
            $settings = array_filter([
                'name' => isset($patch['name']) ? (string) $patch['name'] : null,
                'cpc_bid' => isset($patch['cpc_bid']) ? (float) $patch['cpc_bid'] : null,
            ], fn (mixed $value): bool => $value !== null);
            if ($settings !== []) {
                $this->google->updateAdGroup($connection, $entity->external_id, $settings);
            }

            return;
        }

        $targeting = array_intersect_key($patch, array_flip(AdvancedEditFields::GOOGLE));
        if ($targeting !== []) {
            $this->google->updateManagerCriteria($connection, $entity->external_id, (array) data_get($entity->settings, 'manager_criteria'), $targeting);
        }

        if (array_key_exists('daily_budget', $patch)) {
            if ((int) data_get($entity->settings, 'budget_shared_by') !== 1) {
                throw new EditRefused('This budget is shared with other campaigns, so it is not changed from here.');
            }

            $budgetId = EditCapabilities::googleBudgetId($entity)
                ?? throw new EditRefused('Google did not report which budget this campaign uses.');

            $this->google->updateLiveBudget($connection, $budgetId, (float) $patch['daily_budget']);
        }

        $fields = [
            ...(array_key_exists('name', $patch) ? ['name' => (string) $patch['name']] : []),
            ...(array_key_exists('frequency_caps', $patch) ? ['frequencyCaps' => $patch['frequency_caps']] : []),
            ...(array_key_exists('network_settings', $patch) ? ['networkSettings' => [...(array) data_get($entity->settings, 'network_settings'), ...$patch['network_settings']]] : []),
            ...(array_key_exists('geo_target_type', $patch) ? ['geoTargetTypeSetting' => $patch['geo_target_type']] : []),
            ...$this->bidding($entity, $patch),
            ...$this->runDates($entity, $patch),
        ];

        if ($fields !== []) {
            $this->google->updateLiveCampaign($connection, $entity->external_id, $fields);
        }
    }

    /**
     * The bidding block for a strategy or target change: the strategy as
     * changed or as it is, and the target as changed or as it is. An empty
     * block clears the target; its mask still names the leaf.
     *
     * @param  array<string, mixed>  $patch
     * @return array<string, mixed>
     */
    private function bidding(CampaignPlatformEntity $entity, array $patch): array
    {
        if (array_intersect_key($patch, array_flip(['bid_strategy', 'target_cpa', 'target_roas'])) === []) {
            return [];
        }

        $strategy = strtoupper((string) ($patch['bid_strategy'] ?? EditCapabilities::current($entity, 'bid_strategy')));
        $target = fn (string $field): ?float => is_numeric($value = array_key_exists($field, $patch) ? $patch[$field] : EditCapabilities::current($entity, $field))
            && (float) $value > 0 ? (float) $value : null;
        $channel = (string) data_get($entity->settings, 'channel_type');

        return match ($strategy) {
            'MANUAL_CPC' => $this->google->biddingFor('manual_cpc'),
            'TARGET_SPEND' => $this->google->biddingFor('max_clicks'),
            'MAXIMIZE_CONVERSIONS' => $this->google->biddingFor('target_cpa', $target('target_cpa'), $channel),
            'MAXIMIZE_CONVERSION_VALUE' => ($roas = $target('target_roas')) === null
                ? $this->google->biddingFor('max_conversion_value')
                : $this->google->biddingFor('target_roas', $roas),
            default => throw new EditRefused('Choose maximize conversions, maximize conversion value, maximize clicks or manual CPC.'),
        };
    }

    /**
     * Start and end as Google takes them: "2026-10-07 09:00:00" in the
     * account's zone. Only a moved end is named in the mask, so the start of a
     * running campaign is never touched by an end change.
     *
     * @param  array<string, mixed>  $patch
     * @return array<string, string>
     */
    private function runDates(CampaignPlatformEntity $entity, array $patch): array
    {
        $dates = [];
        $zone = data_get($entity->settings, 'time_zone');

        foreach (['start_time' => 'startDateTime', 'end_time' => 'endDateTime'] as $field => $name) {
            if (! array_key_exists($field, $patch)) {
                continue;
            }

            if (! is_string($zone) || ! in_array($zone, timezone_identifiers_list(), true)) {
                throw new EditRefused('Google did not report the account\'s time zone, so run dates are not changed from here.');
            }

            if (! is_string($patch[$field]) || ($moment = EditCapabilities::moment($patch[$field])) === null) {
                throw new EditRefused('A run date has to be a date and time; Google run dates are not removed from here.');
            }

            $dates[$name] = $moment->setTimezone($zone)->format('Y-m-d H:i:s');
        }

        return $dates;
    }

    /** All-time, so an object that spent and then stopped does not read as never having run. */
    public function delivery(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): array
    {
        $seen = $this->google->readLifetimeDelivery($this->connection($campaign), $entity->entity_type, [$entity->external_id]);
        if (! isset($seen[$entity->external_id]['spend'], $seen[$entity->external_id]['impressions'])) {
            throw new EditRefused('Google did not confirm lifetime delivery. Unknown spend is not zero.');
        }

        return [
            'spend' => (float) $seen[$entity->external_id]['spend'],
            'impressions' => (int) $seen[$entity->external_id]['impressions'],
        ];
    }

    /** Google takes a campaign's ad groups and ads with it. */
    public function delete(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): bool
    {
        if (! in_array($entity->entity_type, ['campaign', 'ad_group', 'ad'], true)) {
            throw new EditRefused('Only a campaign, an ad group or an ad is deleted on Google from here.');
        }

        $this->google->removeEntity(
            $this->connection($campaign),
            $entity->entity_type,
            $entity->external_id,
            $entity->entity_type === 'ad' ? $entity->parent_external_id : null,
        );

        return true;
    }

    /** Google has no copy call: the source is read and recreated, paused, keywords and ads included. */
    public function duplicate(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): string
    {
        $connection = $this->connection($campaign);

        return match ($entity->entity_type) {
            'campaign' => $this->google->duplicateManagerCampaign($connection, $entity->external_id),
            'asset_group' => $this->google->duplicateManagerAssetGroup($connection, (string) $campaign->external_campaign_id, $entity->external_id),
            'ad_group' => (string) $this->google->duplicateAdGroup($connection, $entity->external_id, expectedCampaignId: (string) $campaign->external_campaign_id)['ad_group_id'],
            'ad' => $this->google->duplicateAd($connection, $entity->external_id, $entity->parent_external_id, expectedSourceAdGroupId: $entity->parent_external_id),
            default => throw new EditRefused('Only an ad group or an ad is copied on Google from here.'),
        };
    }

    private function connection(Campaign $campaign): GoogleAdsConnection
    {
        return (GoogleAdsConnection::shared()
            ?? throw new EditRefused(ucfirst(GoogleAdsConnection::missingReason()).'.'))
            ->onCustomer($campaign->ad_account_id);
    }
}
