<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Models\TargetingSet;
use App\Services\GoogleAdsService;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class GoogleUserListSelections
{
    public function __construct(
        private readonly GoogleAdsService $google,
        private readonly TargetingSelections $locations,
    ) {}

    /** @return list<array<string, mixed>> */
    public function discover(Campaign $campaign, ?string $query = null): array
    {
        return array_map(static fn (array $list): array => [
            ...$list,
            'available' => self::eligible($list),
        ], $this->google->userLists($this->connection($campaign), nameSearch: $query));
    }

    /** @return list<array{resource_name: string, name: string, type: string, operation: string, account_id: string, verified_at: string}> */
    public function selected(Campaign $campaign): array
    {
        $values = $campaign->targetingSet()->first()?->options['google_user_lists'] ?? [];

        if (! is_array($values)) {
            throw new RuntimeException('Saved Google audience lists are invalid. Review targeting.');
        }

        foreach ($values as $list) {
            $accountId = preg_replace('/\D/', '', (string) $campaign->ad_account_id);

            if (! is_array($list)
                || $accountId === ''
                || ! preg_match('/^customers\/'.$accountId.'\/userLists\/[0-9]+$/D', (string) ($list['resource_name'] ?? ''))
                || ! is_string($list['name'] ?? null) || trim($list['name']) === ''
                || ! in_array($list['operation'] ?? null, ['include', 'exclude'], true)
                || ! in_array($list['type'] ?? null, ['REMARKETING', 'RULE_BASED'], true)
                || (string) ($list['account_id'] ?? '') !== $accountId) {
                throw new RuntimeException('Saved Google audience list no longer matches this campaign and account.');
            }
        }

        return array_values($values);
    }

    /** @return list<array<string, mixed>> */
    public function verifiedForPublish(Campaign $campaign): array
    {
        $selected = $this->selected($campaign);

        if ($selected === []) {
            return [];
        }

        $connection = $this->connection($campaign);

        foreach ($selected as $list) {
            $fresh = $this->google->userLists($connection, $list['resource_name']);

            if (count($fresh) !== 1 || ! self::eligible($fresh[0])
                || $fresh[0]['resource_name'] !== $list['resource_name']
                || $fresh[0]['name'] !== $list['name'] || $fresh[0]['type'] !== $list['type']) {
                throw new RuntimeException('A saved Google audience list is unavailable or changed. Review it before publishing.');
            }
        }

        return $selected;
    }

    /** @return list<array<string, mixed>> */
    public function searchListSizes(Campaign $campaign): array
    {
        $selected = $this->selected($campaign);

        if ($selected === []) {
            return [];
        }

        $connection = $this->connection($campaign);
        $sizes = [];

        foreach ($selected as $list) {
            $fresh = $this->google->userLists($connection, $list['resource_name']);
            $match = count($fresh) === 1 && $fresh[0]['resource_name'] === $list['resource_name']
                && $fresh[0]['name'] === $list['name'] && $fresh[0]['type'] === $list['type']
                ? $fresh[0] : null;
            $available = $match !== null && self::eligible($match);

            $sizes[] = [
                'resource_name' => $list['resource_name'],
                'name' => $list['name'],
                'operation' => $list['operation'],
                'status' => $available && $match['size_for_search'] !== null ? 'fresh' : 'unavailable',
                'metric' => 'estimated_google_search_list_users',
                'users' => $available ? $match['size_for_search'] : null,
            ];
        }

        return $sizes;
    }

    public function save(Campaign $campaign, string $resourceName, string $operation, int $expectedRevision): TargetingSet
    {
        $connection = $this->connection($campaign);

        if ($campaign->isPublished() || ! in_array($operation, ['include', 'exclude'], true)) {
            throw new RuntimeException('Choose an include or exclude audience on a draft Google Search campaign.');
        }

        $lists = $this->google->userLists($connection, $resourceName);

        if (count($lists) !== 1 || $lists[0]['resource_name'] !== $resourceName || ! self::eligible($lists[0])) {
            throw new RuntimeException('This Google audience list is unavailable for Search targeting.');
        }

        $countries = $this->locations->countries($campaign);

        if ($countries === []) {
            throw new RuntimeException('Select countries before choosing an audience.');
        }

        return DB::transaction(function () use ($campaign, $lists, $resourceName, $operation, $expectedRevision, $countries): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            if ($set === null || $set->mode !== 'override') {
                $set = $this->locations->saveCampaignCountries($campaign, $countries, $expectedRevision);
                $set->refresh();
            }

            $selected = $this->selected($campaign);

            if (collect($selected)->contains(static fn (array $value): bool => $value['resource_name'] === $resourceName)) {
                throw new RuntimeException('This audience is already selected. Remove it before changing include or exclude.');
            }

            if (count($selected) >= 20) {
                throw new RuntimeException('Choose no more than 20 Google audience lists.');
            }

            $list = $lists[0];
            $selected[] = [
                'resource_name' => $resourceName,
                'name' => $list['name'],
                'type' => $list['type'],
                'operation' => $operation,
                'account_id' => preg_replace('/\D/', '', (string) $campaign->ad_account_id),
                'verified_at' => now()->toIso8601String(),
            ];
            $set->update([
                'options' => [...(array) ($set->options ?? []), 'google_user_lists' => $selected],
                'revision' => $set->revision + 1,
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function remove(Campaign $campaign, string $resourceName, int $expectedRevision): TargetingSet
    {
        if ($campaign->isPublished() || $campaign->platform !== 'google') {
            throw new RuntimeException('Only a draft Google Search campaign can remove an audience.');
        }

        return DB::transaction(function () use ($campaign, $resourceName, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first()
                ?? throw new RuntimeException('This campaign has no audience list to remove.');

            if ($set->revision !== $expectedRevision) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $selected = (array) ($set->options['google_user_lists'] ?? []);
            $remaining = array_values(array_filter($selected,
                static fn (mixed $list): bool => ! is_array($list)
                    || ($list['resource_name'] ?? null) !== $resourceName));

            if (count($remaining) === count($selected)) {
                throw new RuntimeException('This audience is not selected on the campaign.');
            }

            $set->update([
                'options' => [...(array) ($set->options ?? []), 'google_user_lists' => $remaining],
                'revision' => $set->revision + 1,
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    private function connection(Campaign $campaign): GoogleAdsConnection
    {
        if ($campaign->platform !== 'google' || ($campaign->campaign_type ?: 'search') !== 'search') {
            throw new RuntimeException('Google audience lists are available for Search campaigns only.');
        }

        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(GoogleAdsConnection::missingReason());

        // An account is still required - an audience list belongs to one, and
        // there is nothing to read without it - but it no longer has to be the
        // configured account. See PublishedLocationReadback.
        if (preg_replace('/\D/', '', (string) $campaign->ad_account_id) === '') {
            throw new RuntimeException('This campaign has no Google Ads account recorded. Choose one first.');
        }

        return $connection->onCustomer((string) $campaign->ad_account_id);
    }

    /** @param array<string, mixed> $list */
    private static function eligible(array $list): bool
    {
        return in_array($list['type'], ['REMARKETING', 'RULE_BASED'], true)
            && $list['access_reason'] === 'OWNED'
            && $list['eligible_for_search'] === true
            && $list['membership_status'] === 'OPEN'
            && $list['access_status'] === 'ENABLED';
    }
}
