<?php

namespace App\Campaigns\Targeting;

use App\Models\Location;
use App\Models\PlatformLocation;
use Illuminate\Support\Facades\DB;

class LocationCatalogImporter
{
    /**
     * Store provider search results as catalog candidates. Targeting still calls
     * LocationDiscovery::select to verify an ID before it can be used.
     *
     * @param  list<array{platform: string, external_id: string, kind: string, name: string, label: string, country_code: string, parent_external_id: string|null, catalog_priority?: int}>  $candidates
     */
    public function store(array $candidates, ?string $priorityName = null): int
    {
        $stored = 0;
        $countries = [];

        foreach (array_chunk($candidates, 250) as $chunk) {
            DB::transaction(function () use ($chunk, $priorityName, &$stored, &$countries): void {
                foreach ($chunk as $candidate) {
                    if (! isset($candidate['platform'], $candidate['external_id'], $candidate['kind'], $candidate['name'], $candidate['label'], $candidate['country_code'])
                        || ! in_array($candidate['platform'], ['meta', 'google', 'linkedin'], true)
                        || ! in_array($candidate['kind'], ['city', 'region', 'dma'], true)
                        || ! preg_match('/^[A-Z]{2}$/D', $candidate['country_code'])
                        || blank($candidate['external_id']) || blank($candidate['name']) || blank($candidate['label'])) {
                        continue;
                    }

                    $countryCode = $candidate['country_code'];
                    $countries[$countryCode] ??= Location::query()->where('type', 'country')->where('iso_code', $countryCode)->first();
                    $country = $countries[$countryCode];

                    if ($country === null) {
                        continue;
                    }

                    $existing = PlatformLocation::query()->where('platform', $candidate['platform'])
                        ->where('external_id', $candidate['external_id'])->first();

                    $priority = max((int) ($existing?->catalog_priority ?? 0),
                        (int) ($candidate['catalog_priority'] ?? 0),
                        $priorityName !== null && mb_strtolower($candidate['name']) === mb_strtolower($priorityName) ? 1 : 0);

                    if ($existing?->status === 'verified') {
                        if ($priority > $existing->catalog_priority) {
                            $existing->update(['catalog_priority' => $priority]);
                        }

                        continue;
                    }

                    $location = Location::query()->updateOrCreate(
                        ['type' => $candidate['kind'], 'source' => $candidate['platform'], 'source_key' => $candidate['external_id']],
                        ['name' => $candidate['name'], 'country_code' => $candidate['country_code'], 'parent_id' => $country->getKey()],
                    );

                    $values = ['location_id' => $location->getKey(), 'parent_external_id' => $candidate['parent_external_id'] ?? null,
                        'provider_name' => $candidate['label'], 'status' => 'unverified', 'verified_at' => null,
                        'catalog_priority' => $priority];

                    if ($existing === null) {
                        PlatformLocation::query()->create(array_merge([
                            'platform' => $candidate['platform'], 'external_id' => $candidate['external_id'],
                        ], $values));
                    } else {
                        $existing->update($values);
                    }
                    $stored++;
                }
            });
        }

        return $stored;
    }
}
