<?php

namespace App\Campaigns;

use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;

class WhaleAdopsReader
{
    public function __construct(private readonly WhaleAdopsTables $tables) {}

    public function isAvailable(): bool
    {
        if (! (bool) config('campaign-performance.adops_enabled', true)) {
            return false;
        }

        return $this->tables->allAdopsTables() !== [];
    }

    /**
     * Distinct campaigns from every arb_adops_* table that has a campaign id.
     * Never reads the app `campaigns` table.
     *
     * @return list<array{
     *     platform: string,
     *     account_id: ?string,
     *     campaign_id: string,
     *     name: string,
     *     status: ?string,
     *     effective_status: ?string,
     *     daily_budget: ?float,
     *     learning_status: ?string,
     *     started_at: ?string
     * }>
     */
    public function campaigns(?string $platform = 'meta', ?string $campaignId = null, ?string $query = null, ?int $limit = null): array
    {
        $seen = [];

        foreach ($this->tables->allAdopsTables() as $table) {
            $this->collectCampaignIdsFromTable($table, $platform, $campaignId, $seen);
        }

        $this->overlayAdopsProfile($seen, 'campaigns');
        $this->overlayAdopsProfile($seen, 'ads');
        $this->overlayAdopsProfile($seen, 'adsets');
        $this->fillAdSetDailyBudgets($seen);
        $this->collectPerformanceCampaignIds($platform, $campaignId, $seen);
        $this->collectRoiCampaignIds($platform, $campaignId, $seen);

        $rows = array_values($seen);

        if (is_string($query) && $query !== '') {
            $needle = strtolower($query);
            $rows = array_values(array_filter(
                $rows,
                fn (array $row): bool => str_contains(strtolower($row['campaign_id']), $needle)
                    || str_contains(strtolower($row['name']), $needle),
            ));
        }

        if ($limit !== null) {
            $rows = array_slice($rows, 0, max(1, $limit));
        }

        return $rows;
    }

    /**
     * Campaigns with at least one stats_daily or stats_hourly row in the last 30 days.
     * Does not scan ROI, affiliate performance, or breakdown tables.
     *
     * @return list<array{
     *     platform: string,
     *     account_id: ?string,
     *     campaign_id: string,
     *     name: string,
     *     status: ?string,
     *     effective_status: ?string,
     *     daily_budget: ?float,
     *     learning_status: ?string,
     *     started_at: ?string
     * }>
     */
    public function campaignsWithRecentStats(?string $platform = 'meta', ?string $campaignId = null, ?int $limit = null): array
    {
        $from = now()->subDays(29)->toDateString();
        $to = now()->toDateString();
        $seen = [];

        // Both families, because the campaign level tables are where campaign
        // level stats actually live.
        //
        // This read only stats_daily and stats_hourly, which resolve to
        // arb_adops_stats_daily and its monthly partitions. The per-campaign
        // rows are in arb_adops_stats_campaign_daily - the campaign_daily and
        // campaign_hourly datasets - so a campaign that had stats was reported
        // as not existing at all: campaign_health answered "No Whale campaign
        // found for that id" for every id, while find_campaign found the same
        // campaign because it enumerates every adops table rather than naming
        // datasets.
        //
        // Added to rather than swapped. Which of the two a given install has is
        // not knowable from here, and scanning a table that is absent costs
        // nothing, where reading the wrong one costs the answer.
        $tables = array_values(array_unique(array_merge(
            $this->tables->tablesFor('campaign_daily', $from, $to),
            $this->tables->tablesFor('campaign_hourly', $from, $to),
            $this->tables->tablesFor('stats_daily', $from, $to),
            $this->tables->tablesFor('stats_hourly', $from, $to),
        )));

        foreach ($tables as $table) {
            $this->collectCampaignIdsFromStatsTable($table, $platform, $campaignId, $from, $to, $seen);
        }

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

        $this->overlayAdopsProfile($seen, 'campaigns');
        $this->overlayAdopsProfile($seen, 'ads');
        $this->overlayAdopsProfile($seen, 'adsets');
        $this->fillAdSetDailyBudgets($seen);
        $this->overlayRoiCampaignNames($seen, $platform);

        $rows = array_values($seen);

        if ($limit !== null) {
            $rows = array_slice($rows, 0, max(1, $limit));
        }

        return $rows;
    }

    /**
     * Objective from arb_adops_campaigns, and a region label from targeting,
     * then geo and region breakdown tables when targeting has no region.
     *
     * @return array{objective: ?string, region_label: ?string}
     */
    public function profileFacts(string $platform, string $campaignId): array
    {
        [$regions, $countries] = $this->targetingPlaces($platform, $campaignId);

        if ($regions === []) {
            [$geoRegions, $geoCountries] = $this->geoPlaces($platform, $campaignId);
            $regions = $geoRegions;
            $countries = array_values(array_unique(array_merge($countries, $geoCountries)));
        }

        return [
            'objective' => $this->campaignObjective($platform, $campaignId),
            'region_label' => $this->joinPlaceLabels($regions !== [] ? $regions : $countries),
        ];
    }

    /**
     * Interests, job titles, and Advantage audience already stored for this campaign.
     *
     * @return array{
     *     countries: list<string>,
     *     age_min: ?int,
     *     age_max: ?int,
     *     interests: list<string>,
     *     job_titles: list<string>,
     *     advantage_audience: bool,
     *     custom_audience: bool
     * }
     */
    public function audienceFacts(string $platform, string $campaignId): array
    {
        $empty = CampaignAudienceFacts::fromRows([]);
        $table = $this->tables->name('targeting');

        if ($table === null || $campaignId === '') {
            return $empty;
        }

        $ids = $this->adSetIds($platform, $campaignId);
        $ids[] = $campaignId;

        try {
            $query = DB::connection('whale')->table($table)->whereIn('entity_id', $ids);
            $platformCol = $this->pick($this->columns($table), ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $rows = [];

            foreach ($query->get() as $row) {
                $rows[] = (array) $row;
            }

            return CampaignAudienceFacts::fromRows($rows);
        } catch (Throwable) {
            return $empty;
        }
    }

    /**
     * Spend, bid, and budget for one campaign, already in major currency units.
     *
     * Null when the warehouse does not have all three. A spend of zero is
     * present. A campaign with no stored spend row is not.
     *
     * @return array{
     *     account_id: ?string,
     *     name: string,
     *     status: ?string,
     *     effective_status: ?string,
     *     currency: ?string,
     *     daily_budget: ?float,
     *     lifetime_budget: ?float,
     *     bid_strategy: ?string,
     *     bid_amount: ?float,
     *     spend: float,
     *     ad_sets: list<array<string, mixed>>
     * }|null
     */
    public function deliveryFigures(string $platform, string $campaignId): ?array
    {
        if ($campaignId === '' || ! $this->isAvailable()) {
            return null;
        }

        $table = $this->tables->name('campaigns');

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

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);

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

        try {
            $query = DB::connection('whale')->table($table)->where($campaignCol, $campaignId);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $row = $query->first();
        } catch (Throwable) {
            return null;
        }

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

        $daily = $this->columnFloat($row, $columns, ['daily_budget']);
        $lifetime = $this->columnFloat($row, $columns, ['lifetime_budget']);
        $bidStrategy = $this->columnString($row, $columns, ['bid_strategy']);
        $bidAmount = $this->columnFloat($row, $columns, ['bid_amount']);
        $adSets = $this->deliveryAdSets($platform, $campaignId);
        $hasBudget = $daily !== null || $lifetime !== null || $this->adSetsHaveAmount($adSets, ['daily_budget', 'lifetime_budget']);
        $hasBid = $bidStrategy !== null || $bidAmount !== null || $this->adSetsHaveBid($adSets);
        $spend = $this->storedLifetimeSpend($platform, $campaignId);

        if (! $hasBudget || ! $hasBid || $spend === null) {
            return null;
        }

        return [
            'account_id' => $this->columnString($row, $columns, ['account_id', 'ad_account_id']),
            'name' => $this->columnString($row, $columns, ['name', 'campaign_name']) ?? $campaignId,
            'status' => $this->columnString($row, $columns, ['status']),
            'effective_status' => $this->columnString($row, $columns, ['effective_status'])
                ?? $this->columnString($row, $columns, ['status']),
            'currency' => $this->columnString($row, $columns, ['currency']),
            'daily_budget' => $daily,
            'lifetime_budget' => $lifetime,
            'bid_strategy' => $bidStrategy,
            'bid_amount' => $bidAmount,
            'spend' => $spend,
            'ad_sets' => $adSets,
        ];
    }

    /**
     * What the campaign is trying to buy: objective, bid, and budget.
     *
     * @return array<string, mixed>
     */
    public function campaignGoals(string $platform, string $campaignId): array
    {
        $table = $this->tables->name('campaigns');

        if ($table === null) {
            return [];
        }

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);

        if ($campaignCol === null) {
            return [];
        }

        $map = [
            'objective' => ['objective'],
            'buying_type' => ['buying_type'],
            'bid_strategy' => ['bid_strategy'],
            'status' => ['effective_status', 'status'],
            'learning_status' => ['learning_status'],
        ];
        $amounts = [
            'bid_amount' => ['bid_amount'],
            'target_cpa' => ['target_cpa'],
            'target_roas' => ['target_roas'],
            'daily_budget' => ['daily_budget'],
            'lifetime_budget' => ['lifetime_budget'],
        ];
        $select = [$campaignCol];
        $chosen = [];

        foreach ([...$map, ...$amounts] as $key => $candidates) {
            $column = $this->pick($columns, $candidates);

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

            $select[] = $column;
            $chosen[$key] = $column;
        }

        try {
            $query = DB::connection('whale')->table($table)->where($campaignCol, $campaignId);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $row = $query->first($select);
        } catch (Throwable) {
            return [];
        }

        if ($row === null) {
            return [];
        }

        $goals = [];

        foreach ($map as $key => $candidates) {
            if (! isset($chosen[$key])) {
                continue;
            }

            $value = $this->nullableString($this->value($row, $chosen[$key]));

            if ($value !== null) {
                $goals[$key] = $value;
            }
        }

        foreach ($amounts as $key => $candidates) {
            if (! isset($chosen[$key])) {
                continue;
            }

            $value = $this->nullableFloat($this->value($row, $chosen[$key]));

            if ($value !== null) {
                $goals[$key] = $value;
            }
        }

        return $goals;
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function deliveryAdSets(string $platform, string $campaignId): array
    {
        $table = $this->tables->name('adsets');

        if ($table === null) {
            return [];
        }

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);

        if ($campaignCol === null) {
            return [];
        }

        $idCol = $this->pick($columns, ['adset_id', 'ad_set_id']);
        $nameCol = $this->pick($columns, ['name', 'adset_name', 'ad_set_name']);
        $statusCol = $this->pick($columns, ['status']);
        $effectiveCol = $this->pick($columns, ['effective_status']);
        $dailyCol = $this->pick($columns, ['daily_budget']);
        $lifetimeCol = $this->pick($columns, ['lifetime_budget']);
        $strategyCol = $this->pick($columns, ['bid_strategy']);
        $amountCol = $this->pick($columns, ['bid_amount']);

        try {
            $query = DB::connection('whale')->table($table)->where($campaignCol, $campaignId);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $rows = [];

            foreach ($query->limit(50)->get() as $row) {
                $status = $statusCol !== null ? $this->nullableString($this->value($row, $statusCol)) : null;

                if (in_array(strtoupper((string) $status), ['ARCHIVED', 'DELETED'], true)) {
                    continue;
                }

                $rows[] = [
                    'id' => $idCol !== null ? $this->nullableString($this->value($row, $idCol)) : null,
                    'name' => $nameCol !== null ? $this->nullableString($this->value($row, $nameCol)) : null,
                    'status' => $status,
                    'effective_status' => $effectiveCol !== null ? $this->nullableString($this->value($row, $effectiveCol)) : $status,
                    'daily_budget' => $dailyCol !== null ? $this->nullableFloat($this->value($row, $dailyCol)) : null,
                    'lifetime_budget' => $lifetimeCol !== null ? $this->nullableFloat($this->value($row, $lifetimeCol)) : null,
                    'bid_strategy' => $strategyCol !== null ? $this->nullableString($this->value($row, $strategyCol)) : null,
                    'bid_amount' => $amountCol !== null ? $this->nullableFloat($this->value($row, $amountCol)) : null,
                    'spend' => null,
                ];
            }

            return $rows;
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * @param  list<array<string, mixed>>  $adSets
     * @param  list<string>  $keys
     */
    private function adSetsHaveAmount(array $adSets, array $keys): bool
    {
        foreach ($adSets as $adSet) {
            foreach ($keys as $key) {
                if (is_numeric($adSet[$key] ?? null)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * @param  list<array<string, mixed>>  $adSets
     */
    private function adSetsHaveBid(array $adSets): bool
    {
        foreach ($adSets as $adSet) {
            if (filled($adSet['bid_strategy'] ?? null) || is_numeric($adSet['bid_amount'] ?? null)) {
                return true;
            }
        }

        return false;
    }

    private function storedLifetimeSpend(string $platform, string $campaignId): ?float
    {
        try {
            $rows = $this->dailyStats($platform, $campaignId, '2010-01-01', now()->toDateString());
        } catch (Throwable) {
            return null;
        }

        if ($rows->isEmpty()) {
            return null;
        }

        return round($rows->sum(fn (PerformanceDay $day): float => $day->spend), 2);
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $candidates
     */
    private function columnString(object $row, array $columns, array $candidates): ?string
    {
        $column = $this->pick($columns, $candidates);

        return $column === null ? null : $this->nullableString($this->value($row, $column));
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $candidates
     */
    private function columnFloat(object $row, array $columns, array $candidates): ?float
    {
        $column = $this->pick($columns, $candidates);

        return $column === null ? null : $this->nullableFloat($this->value($row, $column));
    }

    /**
     * Ad sets stored for one campaign, capped so a review snapshot stays readable.
     *
     * @return list<array<string, mixed>>
     */
    public function reviewAdSets(string $platform, string $campaignId): array
    {
        $table = $this->tables->name('adsets');

        if ($table === null) {
            return [];
        }

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);

        if ($campaignCol === null) {
            return [];
        }

        $idCol = $this->pick($columns, ['adset_id', 'ad_set_id']);
        $nameCol = $this->pick($columns, ['name', 'adset_name', 'ad_set_name']);
        $statusCol = $this->pick($columns, ['effective_status', 'status']);
        $budgetCol = $this->pick($columns, ['daily_budget', 'budget']);
        $goalCol = $this->pick($columns, ['optimization_goal']);
        $billingCol = $this->pick($columns, ['billing_event']);

        try {
            $query = DB::connection('whale')->table($table)->where($campaignCol, $campaignId);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $rows = [];

            foreach ($query->limit(12)->get() as $row) {
                $rows[] = array_filter([
                    'ad_set_id' => $idCol !== null ? $this->nullableString($this->value($row, $idCol)) : null,
                    'name' => $nameCol !== null ? $this->nullableString($this->value($row, $nameCol)) : null,
                    'status' => $statusCol !== null ? $this->nullableString($this->value($row, $statusCol)) : null,
                    'daily_budget' => $budgetCol !== null ? $this->nullableFloat($this->value($row, $budgetCol)) : null,
                    'optimization_goal' => $goalCol !== null ? $this->nullableString($this->value($row, $goalCol)) : null,
                    'billing_event' => $billingCol !== null ? $this->nullableString($this->value($row, $billingCol)) : null,
                ], fn (mixed $value): bool => $value !== null);
            }

            return $rows;
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * Top regions and breakdown segments from the last 30 days.
     *
     * @return array{regions: list<array<string, mixed>>, segments: list<array<string, mixed>>}
     */
    public function reviewBreakdowns(string $platform, string $campaignId): array
    {
        $from = now()->subDays(29)->toDateString();
        $to = now()->toDateString();

        return [
            'regions' => $this->reviewRegions($platform, $campaignId, $from, $to),
            'segments' => $this->reviewSegments($platform, $campaignId, $from, $to),
        ];
    }

    /**
     * @param  array<string, array<string, mixed>>  $seen
     */
    private function collectCampaignIdsFromStatsTable(
        string $table,
        ?string $platform,
        ?string $campaignId,
        string $from,
        string $to,
        array &$seen,
    ): void {
        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
        $dateCol = $this->pick($columns, ['stat_date', 'date']);
        $statHourCol = $this->pick($columns, ['stat_hour']);

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

        $builder = DB::connection('whale')->table($table)->select($campaignCol);
        $platformCol = $this->pick($columns, ['platform']);
        $accountCol = $this->pick($columns, ['account_id', 'ad_account_id']);

        if ($platformCol !== null) {
            $builder->addSelect($platformCol);

            if (is_string($platform) && $platform !== '') {
                $builder->where($platformCol, strtolower($platform));
            }
        }

        if ($accountCol !== null) {
            $builder->addSelect($accountCol);
        }

        if ($dateCol !== null) {
            $builder->whereBetween($dateCol, [$from, $to]);
        } elseif ($statHourCol !== null) {
            $builder->whereBetween($statHourCol, [$from.' 00:00:00', $to.' 23:59:59']);
        }

        if (is_string($campaignId) && $campaignId !== '') {
            $builder->where($campaignCol, $campaignId);
        }

        try {
            foreach ($builder->distinct()->get() as $row) {
                $id = trim((string) $this->value($row, $campaignCol));

                if ($id === '' || isset($seen[$id])) {
                    continue;
                }

                $seen[$id] = [
                    'platform' => strtolower((string) ($platformCol !== null ? ($this->value($row, $platformCol) ?: $platform) : $platform)),
                    'account_id' => $accountCol !== null ? $this->nullableString($this->value($row, $accountCol)) : null,
                    'campaign_id' => $id,
                    'name' => 'Campaign '.$id,
                    'status' => null,
                    'effective_status' => null,
                    'daily_budget' => null,
                    'learning_status' => null,
                    'started_at' => null,
                ];
            }
        } catch (Throwable) {
            // Table is not readable for this window; skip it.
        }
    }

    /**
     * @param  array<string, array<string, mixed>>  $seen
     */
    private function overlayRoiCampaignNames(array &$seen, ?string $platform): void
    {
        if (! $this->whaleTableExists('roi_dashboard_campaign_stats') || $seen === []) {
            return;
        }

        $columns = $this->columns('roi_dashboard_campaign_stats');
        $dateCol = $this->pick($columns, ['date', 'stat_date']);

        $builder = DB::connection('whale')
            ->table('roi_dashboard_campaign_stats')
            ->select('campaign_id', 'campaign_name')
            ->whereIn('campaign_id', array_keys($seen))
            ->whereNotNull('campaign_name')
            ->where('campaign_name', '!=', '');

        if ($dateCol !== null) {
            $builder->addSelect($dateCol)->orderByDesc($dateCol);
        }

        if (is_string($platform) && $platform !== '') {
            $builder->whereRaw('LOWER(platform) = ?', [strtolower($platform)]);
        }

        try {
            foreach ($builder->get() as $row) {
                $id = trim((string) ($row->campaign_id ?? ''));

                if ($id === '' || ! isset($seen[$id])) {
                    continue;
                }

                if ($seen[$id]['name'] !== 'Campaign '.$id) {
                    continue;
                }

                $name = trim((string) ($row->campaign_name ?? ''));

                if ($name !== '') {
                    $seen[$id]['name'] = $name;
                }
            }
        } catch (Throwable) {
            // ROI names are optional enrichment.
        }
    }

    /**
     * @param  array<string, array<string, mixed>>  $seen
     */
    private function collectCampaignIdsFromTable(string $table, ?string $platform, ?string $campaignId, array &$seen): void
    {
        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);

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

        $builder = DB::connection('whale')->table($table)->select($campaignCol);
        $platformCol = $this->pick($columns, ['platform']);
        $accountCol = $this->pick($columns, ['account_id', 'ad_account_id']);

        if ($platformCol !== null) {
            $builder->addSelect($platformCol);

            if (is_string($platform) && $platform !== '') {
                $builder->where($platformCol, strtolower($platform));
            }
        }

        if ($accountCol !== null) {
            $builder->addSelect($accountCol);
        }

        if (is_string($campaignId) && $campaignId !== '') {
            $builder->where($campaignCol, $campaignId);
        }

        try {
            foreach ($builder->distinct()->get() as $row) {
                $id = trim((string) $this->value($row, $campaignCol));

                if ($id === '' || isset($seen[$id])) {
                    continue;
                }

                $seen[$id] = [
                    'platform' => strtolower((string) ($platformCol !== null ? ($this->value($row, $platformCol) ?: $platform) : $platform)),
                    'account_id' => $accountCol !== null ? $this->nullableString($this->value($row, $accountCol)) : null,
                    'campaign_id' => $id,
                    'name' => 'Campaign '.$id,
                    'status' => null,
                    'effective_status' => null,
                    'daily_budget' => null,
                    'learning_status' => null,
                    'started_at' => null,
                ];
            }
        } catch (Throwable) {
            // Table is not a campaign-id grain; skip it.
        }
    }

    /**
     * Campaigns that exist only on the affiliate performance table.
     * An id already collected from arb_adops_* is left unchanged.
     *
     * @param  array<string, array<string, mixed>>  $seen
     */
    private function collectPerformanceCampaignIds(?string $platform, ?string $campaignId, array &$seen): void
    {
        if (! $this->whaleTableExists('arb_adops_campaign_performance')) {
            return;
        }

        $builder = DB::connection('whale')
            ->table('arb_adops_campaign_performance')
            ->select('campaign_id')
            ->distinct();

        if (is_string($campaignId) && $campaignId !== '') {
            $builder->where('campaign_id', $campaignId);
        }

        try {
            foreach ($builder->get() as $row) {
                $id = trim((string) ($row->campaign_id ?? ''));

                if ($id === '' || isset($seen[$id])) {
                    continue;
                }

                $seen[$id] = $this->blankCampaign($id, $platform);
            }
        } catch (Throwable) {
            // Performance table is optional for the campaign list.
        }
    }

    /**
     * ROI dashboard campaigns not already listed.
     * arb_adops_* and arb_adops_campaign_performance keep the row when the id exists in both.
     *
     * @param  array<string, array<string, mixed>>  $seen
     */
    private function collectRoiCampaignIds(?string $platform, ?string $campaignId, array &$seen): void
    {
        if (! $this->whaleTableExists('roi_dashboard_campaign_stats')) {
            return;
        }

        $builder = DB::connection('whale')
            ->table('roi_dashboard_campaign_stats')
            ->select('campaign_id', 'platform', 'campaign_name');

        if (is_string($platform) && $platform !== '') {
            $builder->whereRaw('LOWER(platform) = ?', [strtolower($platform)]);
        }

        if (is_string($campaignId) && $campaignId !== '') {
            $builder->where('campaign_id', $campaignId);
        }

        try {
            foreach ($builder->get() as $row) {
                $id = trim((string) ($row->campaign_id ?? ''));

                if ($id === '' || isset($seen[$id])) {
                    continue;
                }

                $name = trim((string) ($row->campaign_name ?? ''));
                $rowPlatform = strtolower(trim((string) ($row->platform ?? '')));
                $seen[$id] = $this->blankCampaign($id, $rowPlatform !== '' ? $rowPlatform : $platform);
                $seen[$id]['metrics_source'] = 'roi_dashboard';
                if ($name !== '') {
                    $seen[$id]['name'] = $name;
                }
            }
        } catch (Throwable) {
            // ROI table is optional for the campaign list.
        }
    }

    /**
     * @return array{
     *     platform: string,
     *     account_id: null,
     *     campaign_id: string,
     *     name: string,
     *     status: null,
     *     effective_status: null,
     *     daily_budget: null,
     *     learning_status: null,
     *     started_at: null
     * }
     */
    private function blankCampaign(string $id, ?string $platform): array
    {
        return [
            'platform' => strtolower((string) ($platform !== null && $platform !== '' ? $platform : 'meta')),
            'account_id' => null,
            'campaign_id' => $id,
            'name' => 'Campaign '.$id,
            'status' => null,
            'effective_status' => null,
            'daily_budget' => null,
            'learning_status' => null,
            'started_at' => null,
        ];
    }

    private function whaleTableExists(string $table): bool
    {
        try {
            return Schema::connection('whale')->hasTable($table);
        } catch (Throwable) {
            return false;
        }
    }

    /**
     * Campaigns with the budget on ad sets have no campaign daily_budget.
     * The exact daily budget is the sum of the active ad set budgets.
     *
     * @param  array<string, array<string, mixed>>  $seen
     */
    private function fillAdSetDailyBudgets(array &$seen): void
    {
        $missing = [];

        foreach ($seen as $id => $row) {
            if (! is_numeric($row['daily_budget'] ?? null) || (float) $row['daily_budget'] <= 0) {
                $missing[] = (string) $id;
            }
        }

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

        $table = $this->tables->name('adsets');

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

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
        $budgetCol = $this->pick($columns, ['daily_budget']);

        if ($campaignCol === null || $budgetCol === null || ! $this->isSqlIdentifier($campaignCol) || ! $this->isSqlIdentifier($budgetCol)) {
            return;
        }

        $statusCol = $this->pick($columns, ['effective_status']);
        $statusCol = is_string($statusCol) && $this->isSqlIdentifier($statusCol) ? $statusCol : null;

        foreach (array_chunk($missing, 500) as $chunk) {
            $this->applyAdSetBudgetTotals($seen, $chunk, $table, $campaignCol, $budgetCol, $statusCol, true);
        }

        $stillMissing = array_values(array_filter(
            $missing,
            fn (string $id): bool => ! is_numeric($seen[$id]['daily_budget'] ?? null) || (float) $seen[$id]['daily_budget'] <= 0,
        ));

        foreach (array_chunk($stillMissing, 500) as $chunk) {
            $this->applyAdSetBudgetTotals($seen, $chunk, $table, $campaignCol, $budgetCol, null, false);
        }
    }

    /**
     * @param  array<string, array<string, mixed>>  $seen
     * @param  list<string>  $campaignIds
     */
    private function applyAdSetBudgetTotals(
        array &$seen,
        array $campaignIds,
        string $table,
        string $campaignCol,
        string $budgetCol,
        ?string $statusCol,
        bool $activeOnly,
    ): void {
        if ($campaignIds === []) {
            return;
        }

        try {
            $query = DB::connection('whale')->table($table)
                ->select($campaignCol)
                ->selectRaw('SUM('.$budgetCol.') as budget_total')
                ->whereIn($campaignCol, $campaignIds)
                ->where($budgetCol, '>', 0)
                ->groupBy($campaignCol);

            if ($activeOnly && $statusCol !== null) {
                $query->where($statusCol, 'ACTIVE');
            }

            foreach ($query->get() as $row) {
                $id = trim((string) $this->value($row, $campaignCol));
                $total = $this->nullableFloat($row->budget_total ?? null);

                if ($id === '' || ! isset($seen[$id]) || $total === null || $total <= 0) {
                    continue;
                }

                $seen[$id]['daily_budget'] = $total;
            }
        } catch (Throwable) {
            // Ad set budgets are optional enrichment.
        }
    }

    private function isSqlIdentifier(string $column): bool
    {
        return preg_match('/^[A-Za-z0-9_]+$/', $column) === 1;
    }

    /**
     * @param  array<string, array<string, mixed>>  $seen
     */
    private function overlayAdopsProfile(array &$seen, string $dataset): void
    {
        $table = $this->tables->name($dataset);

        if ($table === null || $seen === []) {
            return;
        }

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);

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

        $nameCol = $this->pick($columns, ['name', 'campaign_name']);
        $platformCol = $this->pick($columns, ['platform']);
        $accountCol = $this->pick($columns, ['account_id', 'ad_account_id']);
        $statusCol = $this->pick($columns, ['status']);
        $effectiveCol = $this->pick($columns, ['effective_status', 'serving_status', 'platform_status']);
        $budgetCol = $this->pick($columns, ['daily_budget', 'budget']);
        $learningCol = $this->pick($columns, ['learning_status', 'learning_stage']);
        $startedCol = $this->pick($columns, ['start_date', 'started_at', 'created_at_platform']);
        $objectiveCol = $this->pick($columns, ['objective']);

        try {
            $rows = DB::connection('whale')->table($table)
                ->whereIn($campaignCol, array_keys($seen))
                ->get();
        } catch (Throwable) {
            return;
        }

        foreach ($rows as $row) {
            $id = trim((string) $this->value($row, $campaignCol));

            if ($id === '' || ! isset($seen[$id])) {
                continue;
            }

            $name = $nameCol !== null ? trim((string) $this->value($row, $nameCol)) : '';
            $placeholder = $seen[$id]['name'] === 'Campaign '.$id;

            if ($name !== '' && ($placeholder || $dataset === 'campaigns')) {
                $seen[$id]['name'] = $name;
            }

            if ($platformCol !== null) {
                $platform = strtolower(trim((string) $this->value($row, $platformCol)));
                if ($platform !== '') {
                    $seen[$id]['platform'] = $platform;
                }
            }

            if ($accountCol !== null && $seen[$id]['account_id'] === null) {
                $seen[$id]['account_id'] = $this->nullableString($this->value($row, $accountCol));
            }

            if ($statusCol !== null && $seen[$id]['status'] === null) {
                $seen[$id]['status'] = $this->nullableString($this->value($row, $statusCol));
            }

            if ($effectiveCol !== null && $seen[$id]['effective_status'] === null) {
                $seen[$id]['effective_status'] = $this->nullableString($this->value($row, $effectiveCol));
            }

            if ($dataset !== 'adsets' && $budgetCol !== null && $seen[$id]['daily_budget'] === null) {
                $seen[$id]['daily_budget'] = $this->nullableFloat($this->value($row, $budgetCol));
            }

            if ($learningCol !== null && $seen[$id]['learning_status'] === null) {
                $seen[$id]['learning_status'] = $this->nullableString($this->value($row, $learningCol));
            }

            if ($startedCol !== null && $seen[$id]['started_at'] === null) {
                $seen[$id]['started_at'] = $this->nullableString($this->value($row, $startedCol));
            }

            if ($objectiveCol !== null && ($seen[$id]['objective'] ?? null) === null) {
                $seen[$id]['objective'] = $this->nullableString($this->value($row, $objectiveCol));
            }
        }
    }

    /**
     * @return Collection<int, PerformanceDay>
     */
    public function dailyStats(string $platform, string $campaignId, string $from, string $to): Collection
    {
        $rows = $this->metricRows('campaign_daily', 'stats_daily', $platform, $campaignId, $from, $to, false);
        $landingPageViews = $this->landingPageViewsByDate($platform, $campaignId, $from, $to);

        return $rows->map(function (array $row) use ($landingPageViews): PerformanceDay {
            $clicks = (int) $row['clicks'];
            $impressions = (int) $row['impressions'];
            $spend = (float) $row['spend'];
            $date = Carbon::parse($row['stat_date'])->toDateString();

            $conversions = (int) ($row['conversions'] ?? 0);
            $conversionValue = round((float) ($row['conversion_value'] ?? 0), 2);
            $fromStats = isset($row['landing_page_views']) && $row['landing_page_views'] !== null
                ? (int) $row['landing_page_views']
                : null;

            return new PerformanceDay(
                stat_date: Carbon::parse($row['stat_date'])->startOfDay(),
                spend: $spend,
                impressions: $impressions,
                clicks: $clicks,
                cpc: $clicks > 0 ? round($spend / $clicks, 4) : null,
                ctr: $impressions > 0 ? round($clicks / $impressions, 4) : null,
                conversions: $conversions,
                conversion_value: $conversionValue,
                reach: isset($row['reach']) ? (int) $row['reach'] : null,
                link_clicks: isset($row['link_clicks']) ? (int) $row['link_clicks'] : null,
                outbound_clicks: isset($row['outbound_clicks']) ? (int) $row['outbound_clicks'] : null,
                landing_page_views: $landingPageViews[$date] ?? $fromStats,
            );
        })->values();
    }

    /**
     * @return Collection<int, PerformanceHour>
     */
    public function hourlyStats(string $platform, string $campaignId, Carbon $since): Collection
    {
        $from = $since->toDateString();
        $to = now()->toDateString();
        $rows = $this->metricRows('campaign_hourly', 'stats_hourly', $platform, $campaignId, $from, $to, true);

        return $rows
            ->map(function (array $row) use ($since): ?PerformanceHour {
                $hour = $this->statHour($row);

                if ($hour === null || $hour->lt($since)) {
                    return null;
                }

                $clicks = (int) $row['clicks'];
                $impressions = (int) $row['impressions'];
                $spend = (float) $row['spend'];

                return new PerformanceHour(
                    stat_hour: $hour,
                    spend: $spend,
                    impressions: $impressions,
                    clicks: $clicks,
                    cpc: $clicks > 0 ? round($spend / $clicks, 4) : null,
                    ctr: $impressions > 0 ? round($clicks / $impressions, 4) : null,
                );
            })
            ->filter()
            ->sortBy(fn (PerformanceHour $row): int => $row->stat_hour->timestamp)
            ->values();
    }

    /**
     * @return array<string, array{spend: float, clicks: int, impressions: int, conversions: int}>
     */
    public function sevenDayTotals(string $platform, string $since): array
    {
        $to = now()->toDateString();
        // Ad-daily and campaign-daily hold the same totals. Adding both doubled
        // the list. Prefer the ad-daily tables, and use campaign-daily only when
        // those partitions are absent — the same order as dailyStats().
        $tables = $this->tables->tablesFor('stats_daily', $since, $to);

        if ($tables === []) {
            $tables = $this->tables->tablesFor('campaign_daily', $since, $to);
        }

        $totals = [];

        foreach ($tables as $name) {
            $columns = $this->columns($name);
            $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
            $dateCol = $this->pick($columns, ['stat_date', 'date']);
            $spendCol = $this->pick($columns, ['spend', 'cost']);
            $clicksCol = $this->clickColumn($columns);
            $impressionsCol = $this->pick($columns, ['impressions', 'impr']);
            $conversionsCol = $this->pick($columns, ['conversions']);

            if ($campaignCol === null || $dateCol === null || $spendCol === null) {
                continue;
            }

            $builder = DB::connection('whale')->table($name)
                ->where($dateCol, '>=', $since)
                ->selectRaw($campaignCol.' as campaign_id')
                ->selectRaw('SUM('.$spendCol.') as spend')
                ->selectRaw($clicksCol !== null ? 'SUM('.$clicksCol.') as clicks' : '0 as clicks')
                ->selectRaw($impressionsCol !== null ? 'SUM('.$impressionsCol.') as impressions' : '0 as impressions')
                ->selectRaw($conversionsCol !== null ? 'SUM('.$conversionsCol.') as conversions' : '0 as conversions')
                ->groupBy($campaignCol);

            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $builder->where($platformCol, $platform);
            }

            try {
                foreach ($builder->get() as $row) {
                    $id = trim((string) $row->campaign_id);

                    if ($id === '') {
                        continue;
                    }

                    $current = $totals[$id] ?? ['spend' => 0.0, 'clicks' => 0, 'impressions' => 0, 'conversions' => 0];
                    $totals[$id] = [
                        'spend' => $current['spend'] + (float) $row->spend,
                        'clicks' => $current['clicks'] + (int) $row->clicks,
                        'impressions' => $current['impressions'] + (int) $row->impressions,
                        'conversions' => $current['conversions'] + (int) ($row->conversions ?? 0),
                    ];
                }
            } catch (Throwable) {
                continue;
            }
        }

        foreach ($totals as $id => $row) {
            $totals[$id]['spend'] = round($row['spend'], 2);
        }

        return $totals;
    }

    /**
     * @return array{status: ?string, last_success_at: ?string, data_through: ?string, error: ?string}|null
     */
    public function syncStatus(string $platform, ?string $accountId, string $dataset): ?array
    {
        $table = $this->tables->name('sync_status');

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

        $columns = $this->columns($table);
        $platformCol = $this->pick($columns, ['platform']);
        $datasetCol = $this->pick($columns, ['dataset']);

        if ($platformCol === null || $datasetCol === null) {
            return null;
        }

        $builder = DB::connection('whale')->table($table)
            ->where($platformCol, $platform)
            ->where($datasetCol, $dataset);

        $accountCol = $this->pick($columns, ['account_id', 'ad_account_id']);

        if ($accountCol !== null && is_string($accountId) && $accountId !== '') {
            $builder->where($accountCol, $accountId);
        }

        try {
            $row = $builder->orderByDesc($this->pick($columns, ['last_success_at', 'updated_at']) ?? $datasetCol)->first();
        } catch (Throwable) {
            return null;
        }

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

        $statusCol = $this->pick($columns, ['status']);
        $successCol = $this->pick($columns, ['last_success_at']);
        $throughCol = $this->pick($columns, ['data_through']);
        $errorCol = $this->pick($columns, ['error', 'last_error']);

        return [
            'status' => $statusCol !== null ? $this->nullableString($this->value($row, $statusCol)) : null,
            'last_success_at' => $successCol !== null ? $this->nullableString($this->value($row, $successCol)) : null,
            'data_through' => $throughCol !== null ? $this->nullableString($this->value($row, $throughCol)) : null,
            'error' => $errorCol !== null ? $this->nullableString($this->value($row, $errorCol)) : null,
        ];
    }

    /**
     * @return array{status: ?string, last_success_at: ?string, data_through: ?string, error: ?string}|null
     */
    public function latestIngest(string $platform, ?string $accountId, string $dataset): ?array
    {
        return $this->syncStatus($platform, $accountId, $dataset)
            ?? $this->syncStatus($platform, $accountId, $dataset.'_backfill')
            ?? $this->syncStatus($platform, $accountId, 'structure');
    }

    /**
     * @param  array{status: ?string, last_success_at: ?string, data_through: ?string, error: ?string}|null  $sync
     */
    public function ingestFailed(?array $sync): bool
    {
        if ($sync === null) {
            return false;
        }

        return in_array(strtolower((string) ($sync['status'] ?? '')), ['failed', 'error'], true);
    }

    public function ingestError(string $platform, ?string $accountId, string $dataset): ?string
    {
        $sync = $this->latestIngest($platform, $accountId, $dataset);

        if (! $this->ingestFailed($sync)) {
            return null;
        }

        return $sync['error'] ?? 'Whale ingest reported a failure.';
    }

    /**
     * @return Collection<int, array{stat_date: string, spend: float, impressions: int, clicks: int, hour: ?int, stat_hour: ?string}>
     */
    private function metricRows(
        string $rollupDataset,
        string $detailDataset,
        string $platform,
        string $campaignId,
        string $from,
        string $to,
        bool $hourly,
    ): Collection {
        $tables = $this->tables->tablesFor($detailDataset, $from, $to);

        if ($tables === []) {
            $tables = $this->tables->tablesFor($rollupDataset, $from, $to);
        }

        $rows = collect();

        foreach ($tables as $table) {
            foreach ($this->readMetricTable($table, $platform, $campaignId, $from, $to, $hourly) as $row) {
                $key = $hourly
                    ? $row['stat_date'].'|'.($row['hour'] ?? $row['stat_hour'] ?? '')
                    : $row['stat_date'];

                if (! $rows->has($key)) {
                    $rows->put($key, $row);

                    continue;
                }

                $existing = $rows->get($key);
                $rows->put($key, [
                    ...$existing,
                    'spend' => $existing['spend'] + $row['spend'],
                    'impressions' => $existing['impressions'] + $row['impressions'],
                    'clicks' => $existing['clicks'] + $row['clicks'],
                    'conversions' => (int) ($existing['conversions'] ?? 0) + (int) ($row['conversions'] ?? 0),
                    'conversion_value' => (float) ($existing['conversion_value'] ?? 0) + (float) ($row['conversion_value'] ?? 0),
                    'reach' => (int) ($existing['reach'] ?? 0) + (int) ($row['reach'] ?? 0),
                    'link_clicks' => (int) ($existing['link_clicks'] ?? 0) + (int) ($row['link_clicks'] ?? 0),
                    'outbound_clicks' => (int) ($existing['outbound_clicks'] ?? 0) + (int) ($row['outbound_clicks'] ?? 0),
                    'landing_page_views' => $this->addNullableInt(
                        $existing['landing_page_views'] ?? null,
                        $row['landing_page_views'] ?? null,
                    ),
                ]);
            }
        }

        return $rows->values();
    }

    /**
     * @return list<array{stat_date: string, spend: float, impressions: int, clicks: int, conversions: int, conversion_value: float, hour: ?int, stat_hour: ?string}>
     */
    private function readMetricTable(
        string $table,
        string $platform,
        string $campaignId,
        string $from,
        string $to,
        bool $hourly,
    ): array {
        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
        $dateCol = $this->pick($columns, ['stat_date', 'date']);
        $spendCol = $this->pick($columns, ['spend', 'cost']);

        if ($campaignCol === null || $dateCol === null || $spendCol === null) {
            return [];
        }

        $builder = DB::connection('whale')->table($table)
            ->where($campaignCol, $campaignId)
            ->whereBetween($dateCol, [$from, $to]);

        $platformCol = $this->pick($columns, ['platform']);

        if ($platformCol !== null) {
            $builder->where($platformCol, $platform);
        }

        $hourCol = $this->pick($columns, ['hour', 'hour_of_day']);
        $statHourCol = $this->pick($columns, ['stat_hour']);
        $clicksCol = $this->clickColumn($columns);
        $impressionsCol = $this->pick($columns, ['impressions', 'impr']);
        $conversionsCol = $this->pick($columns, ['conversions']);
        $conversionValueCol = $this->pick($columns, ['conversion_value', 'conversions_value']);
        $reachCol = $this->pick($columns, ['reach']);
        $linkClicksCol = $this->pick($columns, ['link_clicks']);
        $outboundClicksCol = $this->pick($columns, ['outbound_clicks']);
        $landingPageViewsCol = $this->pick($columns, ['landing_page_views']);
        $reachSelect = $reachCol !== null ? 'SUM('.$reachCol.') as reach' : '0 as reach';
        $linkSelect = $linkClicksCol !== null ? 'SUM('.$linkClicksCol.') as link_clicks' : '0 as link_clicks';
        $outboundSelect = $outboundClicksCol !== null ? 'SUM('.$outboundClicksCol.') as outbound_clicks' : '0 as outbound_clicks';
        $lpvSelect = $landingPageViewsCol !== null ? 'SUM('.$landingPageViewsCol.') as landing_page_views' : 'null as landing_page_views';

        if ($hourly && $hourCol !== null) {
            $builder->selectRaw($dateCol.' as stat_date')
                ->selectRaw($hourCol.' as hour')
                ->selectRaw('SUM('.$spendCol.') as spend')
                ->selectRaw($clicksCol !== null ? 'SUM('.$clicksCol.') as clicks' : '0 as clicks')
                ->selectRaw($impressionsCol !== null ? 'SUM('.$impressionsCol.') as impressions' : '0 as impressions')
                ->selectRaw($conversionsCol !== null ? 'SUM('.$conversionsCol.') as conversions' : '0 as conversions')
                ->selectRaw($conversionValueCol !== null ? 'SUM('.$conversionValueCol.') as conversion_value' : '0 as conversion_value')
                ->selectRaw($reachSelect)
                ->selectRaw($linkSelect)
                ->selectRaw($outboundSelect)
                ->selectRaw($lpvSelect)
                ->groupBy($dateCol, $hourCol);
        } elseif ($hourly && $statHourCol !== null) {
            $builder->selectRaw($statHourCol.' as stat_hour')
                ->selectRaw('SUM('.$spendCol.') as spend')
                ->selectRaw($clicksCol !== null ? 'SUM('.$clicksCol.') as clicks' : '0 as clicks')
                ->selectRaw($impressionsCol !== null ? 'SUM('.$impressionsCol.') as impressions' : '0 as impressions')
                ->selectRaw($conversionsCol !== null ? 'SUM('.$conversionsCol.') as conversions' : '0 as conversions')
                ->selectRaw($conversionValueCol !== null ? 'SUM('.$conversionValueCol.') as conversion_value' : '0 as conversion_value')
                ->selectRaw($reachSelect)
                ->selectRaw($linkSelect)
                ->selectRaw($outboundSelect)
                ->selectRaw($lpvSelect)
                ->groupBy($statHourCol);
        } else {
            $builder->selectRaw($dateCol.' as stat_date')
                ->selectRaw('SUM('.$spendCol.') as spend')
                ->selectRaw($clicksCol !== null ? 'SUM('.$clicksCol.') as clicks' : '0 as clicks')
                ->selectRaw($impressionsCol !== null ? 'SUM('.$impressionsCol.') as impressions' : '0 as impressions')
                ->selectRaw($conversionsCol !== null ? 'SUM('.$conversionsCol.') as conversions' : '0 as conversions')
                ->selectRaw($conversionValueCol !== null ? 'SUM('.$conversionValueCol.') as conversion_value' : '0 as conversion_value')
                ->selectRaw($reachSelect)
                ->selectRaw($linkSelect)
                ->selectRaw($outboundSelect)
                ->selectRaw($lpvSelect)
                ->groupBy($dateCol);
        }

        try {
            return $builder->get()->map(function (object $row): array {
                $statHour = isset($row->stat_hour) ? $this->nullableString($row->stat_hour) : null;
                $date = isset($row->stat_date) ? (string) $row->stat_date : ($statHour !== null ? substr($statHour, 0, 10) : '');

                return [
                    'stat_date' => $date,
                    'spend' => (float) ($row->spend ?? 0),
                    'impressions' => (int) ($row->impressions ?? 0),
                    'clicks' => (int) ($row->clicks ?? 0),
                    'conversions' => (int) ($row->conversions ?? 0),
                    'conversion_value' => (float) ($row->conversion_value ?? 0),
                    'reach' => (int) ($row->reach ?? 0),
                    'link_clicks' => (int) ($row->link_clicks ?? 0),
                    'outbound_clicks' => (int) ($row->outbound_clicks ?? 0),
                    'landing_page_views' => isset($row->landing_page_views) && $row->landing_page_views !== null
                        ? (int) $row->landing_page_views
                        : null,
                    'hour' => isset($row->hour) ? (int) $row->hour : null,
                    'stat_hour' => $statHour,
                ];
            })->all();
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * Stats daily tables do not store landing page views. Those live on
     * conversions_daily as landing_page_view / omni_landing_page_view.
     *
     * @return array<string, int>
     */
    private function landingPageViewsByDate(string $platform, string $campaignId, string $from, string $to): array
    {
        $byDate = [];

        foreach ($this->tables->tablesFor('conversions_daily', $from, $to) as $table) {
            $columns = $this->tables->columns($table);
            $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
            $dateCol = $this->pick($columns, ['stat_date', 'date']);
            $actionCol = $this->pick($columns, ['action_name']);
            $countCol = $this->pick($columns, ['conversions']);

            if ($campaignCol === null || $dateCol === null || $actionCol === null || $countCol === null) {
                continue;
            }

            $builder = DB::connection('whale')->table($table)
                ->where($campaignCol, $campaignId)
                ->whereBetween($dateCol, [$from, $to]);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $builder->where($platformCol, $platform);
            }

            try {
                foreach ($builder->get() as $row) {
                    $kind = match (strtolower(trim((string) ($row->{$actionCol} ?? '')))) {
                        'omni_landing_page_view' => 'omni',
                        'landing_page_view' => 'landing',
                        default => null,
                    };

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

                    $date = (string) ($row->{$dateCol} ?? '');
                    $count = is_numeric($row->{$countCol} ?? null) ? (float) $row->{$countCol} : null;

                    if ($date === '' || $count === null) {
                        continue;
                    }

                    $byDate[$date][$kind] = ($byDate[$date][$kind] ?? 0) + $count;
                }
            } catch (Throwable) {
                continue;
            }
        }

        $views = [];

        foreach ($byDate as $date => $kinds) {
            $views[$date] = (int) round((float) ($kinds['omni'] ?? $kinds['landing'] ?? 0));
        }

        return $views;
    }

    private function addNullableInt(mixed $left, mixed $right): ?int
    {
        if (! is_numeric($left) && ! is_numeric($right)) {
            return null;
        }

        return (int) ($left ?? 0) + (int) ($right ?? 0);
    }

    /**
     * @param  array{stat_date: string, hour: ?int, stat_hour: ?string}  $row
     */
    private function statHour(array $row): ?Carbon
    {
        if (is_string($row['stat_hour']) && $row['stat_hour'] !== '') {
            return Carbon::parse($row['stat_hour'])->startOfHour();
        }

        if ($row['stat_date'] === '' || $row['hour'] === null) {
            return null;
        }

        return Carbon::parse($row['stat_date'])->startOfDay()->setHour($row['hour']);
    }

    private function campaignObjective(string $platform, string $campaignId): ?string
    {
        $table = $this->tables->name('campaigns');

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

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
        $objectiveCol = $this->pick($columns, ['objective']);

        if ($campaignCol === null || $objectiveCol === null) {
            return null;
        }

        try {
            $query = DB::connection('whale')->table($table)->where($campaignCol, $campaignId);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            return $this->nullableString($query->value($objectiveCol));
        } catch (Throwable) {
            return null;
        }
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function reviewRegions(string $platform, string $campaignId, string $from, string $to): array
    {
        $totals = [];

        foreach ($this->tables->tablesFor('stats_geo_daily', $from, $to) as $table) {
            $columns = $this->columns($table);
            $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
            $regionCol = $this->pick($columns, ['region']);
            $countryCol = $this->pick($columns, ['country']);

            if ($campaignCol === null || ($regionCol === null && $countryCol === null)) {
                continue;
            }

            $spendCol = $this->pick($columns, ['spend', 'cost']);
            $impressionCol = $this->pick($columns, ['impressions']);
            $clickCol = $this->clickColumn($columns);

            $dateCol = $this->pick($columns, ['stat_date', 'date']);

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

            try {
                $query = DB::connection('whale')->table($table)
                    ->where($campaignCol, $campaignId)
                    ->whereBetween($dateCol, [$from, $to]);
                $platformCol = $this->pick($columns, ['platform']);

                if ($platformCol !== null) {
                    $query->where($platformCol, $platform);
                }

                $select = array_values(array_filter([$regionCol, $countryCol, $spendCol, $impressionCol, $clickCol]));

                foreach ($query->limit(400)->get($select) as $row) {
                    $label = $regionCol !== null
                        ? $this->nullableString($row->{$regionCol} ?? null)
                        : $this->nullableString($row->{$countryCol} ?? null);

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

                    $current = $totals[$label] ?? ['label' => $label, 'spend' => 0.0, 'impressions' => 0, 'clicks' => 0];
                    $totals[$label] = [
                        'label' => $label,
                        'spend' => round($current['spend'] + (float) ($spendCol !== null ? ($row->{$spendCol} ?? 0) : 0), 2),
                        'impressions' => $current['impressions'] + (int) ($impressionCol !== null ? ($row->{$impressionCol} ?? 0) : 0),
                        'clicks' => $current['clicks'] + (int) ($clickCol !== null ? ($row->{$clickCol} ?? 0) : 0),
                    ];
                }
            } catch (Throwable) {
                continue;
            }
        }

        return $this->topDeliveryRows($totals);
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function reviewSegments(string $platform, string $campaignId, string $from, string $to): array
    {
        $totals = [];

        foreach ($this->tables->tablesFor('stats_breakdown_daily', $from, $to) as $table) {
            $columns = $this->columns($table);
            $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
            $dimensionCol = $this->pick($columns, ['dimension']);
            $valueCol = $this->pick($columns, ['value_1', 'value']);
            $dateCol = $this->pick($columns, ['stat_date', 'date']);

            if ($campaignCol === null || $dimensionCol === null || $valueCol === null || $dateCol === null) {
                continue;
            }

            $spendCol = $this->pick($columns, ['spend', 'cost']);
            $impressionCol = $this->pick($columns, ['impressions']);
            $clickCol = $this->clickColumn($columns);

            try {
                $query = DB::connection('whale')->table($table)
                    ->where($campaignCol, $campaignId)
                    ->whereBetween($dateCol, [$from, $to])
                    ->whereIn($dimensionCol, ['placement', 'publisher_platform', 'age', 'gender', 'device']);
                $platformCol = $this->pick($columns, ['platform']);

                if ($platformCol !== null) {
                    $query->where($platformCol, $platform);
                }

                $select = array_values(array_filter([$dimensionCol, $valueCol, $spendCol, $impressionCol, $clickCol]));

                foreach ($query->limit(400)->get($select) as $row) {
                    $dimension = $this->nullableString($row->{$dimensionCol} ?? null);
                    $value = $this->nullableString($row->{$valueCol} ?? null);

                    if ($dimension === null || $value === null) {
                        continue;
                    }

                    $key = $dimension.'|'.$value;
                    $current = $totals[$key] ?? ['dimension' => $dimension, 'value' => $value, 'spend' => 0.0, 'impressions' => 0, 'clicks' => 0];
                    $totals[$key] = [
                        'dimension' => $dimension,
                        'value' => $value,
                        'spend' => round($current['spend'] + (float) ($spendCol !== null ? ($row->{$spendCol} ?? 0) : 0), 2),
                        'impressions' => $current['impressions'] + (int) ($impressionCol !== null ? ($row->{$impressionCol} ?? 0) : 0),
                        'clicks' => $current['clicks'] + (int) ($clickCol !== null ? ($row->{$clickCol} ?? 0) : 0),
                    ];
                }
            } catch (Throwable) {
                continue;
            }
        }

        return $this->topDeliveryRows($totals);
    }

    /**
     * @param  array<string, array<string, mixed>>  $totals
     * @return list<array<string, mixed>>
     */
    private function topDeliveryRows(array $totals): array
    {
        $rows = array_values($totals);
        usort($rows, fn (array $left, array $right): int => ((float) $right['spend'] <=> (float) $left['spend']));

        return array_slice($rows, 0, 8);
    }

    /**
     * @return array{0: list<string>, 1: list<string>}
     */
    private function targetingPlaces(string $platform, string $campaignId): array
    {
        $table = $this->tables->name('targeting');

        if ($table === null) {
            return [[], []];
        }

        $columns = $this->columns($table);
        $entityCol = $this->pick($columns, ['entity_id']);
        $regionCol = $this->pick($columns, ['regions', 'region']);
        $countryCol = $this->pick($columns, ['countries', 'country']);

        if ($entityCol === null || ($regionCol === null && $countryCol === null)) {
            return [[], []];
        }

        $ids = $this->adSetIds($platform, $campaignId);
        $ids[] = $campaignId;

        try {
            $query = DB::connection('whale')->table($table)->whereIn($entityCol, $ids);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $select = array_values(array_filter([$regionCol, $countryCol]));
            $regions = [];
            $countries = [];

            foreach ($query->get($select) as $row) {
                if ($regionCol !== null) {
                    $regions = array_merge($regions, $this->storedPlaceLabels($row->{$regionCol} ?? null));
                }

                if ($countryCol !== null) {
                    $countries = array_merge($countries, $this->storedPlaceLabels($row->{$countryCol} ?? null));
                }
            }

            return [$regions, $countries];
        } catch (Throwable) {
            return [[], []];
        }
    }

    /**
     * @return list<string>
     */
    private function adSetIds(string $platform, string $campaignId): array
    {
        $table = $this->tables->name('adsets');

        if ($table === null) {
            return [];
        }

        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
        $adSetCol = $this->pick($columns, ['adset_id', 'ad_set_id']);

        if ($campaignCol === null || $adSetCol === null) {
            return [];
        }

        try {
            $query = DB::connection('whale')->table($table)->where($campaignCol, $campaignId);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            return $query->pluck($adSetCol)
                ->map(fn (mixed $id): string => trim((string) $id))
                ->filter(fn (string $id): bool => $id !== '')
                ->values()
                ->all();
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * @return array{0: list<string>, 1: list<string>}
     */
    private function geoPlaces(string $platform, string $campaignId): array
    {
        $from = now()->subDays(89)->toDateString();
        $to = now()->toDateString();
        $regions = [];
        $countries = [];

        foreach ($this->tables->tablesFor('stats_geo_daily', $from, $to) as $table) {
            [$tableRegions, $tableCountries] = $this->geoDailyPlaces($table, $platform, $campaignId);
            $regions = array_merge($regions, $tableRegions);
            $countries = array_merge($countries, $tableCountries);
        }

        foreach ($this->tables->tablesFor('stats_breakdown_daily', $from, $to) as $table) {
            $regions = array_merge($regions, $this->breakdownRegions($table, $platform, $campaignId));
        }

        return [$regions, $countries];
    }

    /**
     * @return array{0: list<string>, 1: list<string>}
     */
    private function geoDailyPlaces(string $table, string $platform, string $campaignId): array
    {
        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
        $regionCol = $this->pick($columns, ['region']);
        $countryCol = $this->pick($columns, ['country']);

        if ($campaignCol === null || ($regionCol === null && $countryCol === null)) {
            return [[], []];
        }

        try {
            $query = DB::connection('whale')->table($table)->where($campaignCol, $campaignId);
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $select = array_values(array_filter([$regionCol, $countryCol]));
            $regions = [];
            $countries = [];

            foreach ($query->distinct()->limit(50)->get($select) as $row) {
                if ($regionCol !== null) {
                    $region = $this->nullableString($row->{$regionCol} ?? null);

                    if ($region !== null) {
                        $regions[] = $region;
                    }
                }

                if ($countryCol !== null) {
                    $country = $this->nullableString($row->{$countryCol} ?? null);

                    if ($country !== null) {
                        $countries[] = $country;
                    }
                }
            }

            return [$regions, $countries];
        } catch (Throwable) {
            return [[], []];
        }
    }

    /**
     * @return list<string>
     */
    private function breakdownRegions(string $table, string $platform, string $campaignId): array
    {
        $columns = $this->columns($table);
        $campaignCol = $this->pick($columns, ['campaign_id', 'external_campaign_id']);
        $dimensionCol = $this->pick($columns, ['dimension']);
        $valueCol = $this->pick($columns, ['value_1']);

        if ($campaignCol === null || $dimensionCol === null || $valueCol === null) {
            return [];
        }

        try {
            $query = DB::connection('whale')->table($table)
                ->where($campaignCol, $campaignId)
                ->where($dimensionCol, 'region');
            $platformCol = $this->pick($columns, ['platform']);

            if ($platformCol !== null) {
                $query->where($platformCol, $platform);
            }

            $regions = [];

            foreach ($query->distinct()->limit(50)->pluck($valueCol) as $value) {
                $region = $this->nullableString($value);

                if ($region !== null) {
                    $regions[] = $region;
                }
            }

            return $regions;
        } catch (Throwable) {
            return [];
        }
    }

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

            if ($trimmed === '' || $trimmed === 'null' || $trimmed === '[]') {
                return [];
            }

            $decoded = json_decode($trimmed, true);
            $value = is_array($decoded) ? $decoded : [$trimmed];
        }

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

        $labels = [];

        foreach ($value as $item) {
            if (is_string($item)) {
                $item = trim($item);

                if ($item !== '') {
                    $labels[] = $item;
                }

                continue;
            }

            if (! is_array($item)) {
                continue;
            }

            $name = $item['name'] ?? null;

            if (is_string($name) && trim($name) !== '') {
                $labels[] = trim($name);
            }
        }

        return $labels;
    }

    /**
     * @param  list<string>  $labels
     */
    private function joinPlaceLabels(array $labels): ?string
    {
        $unique = [];

        foreach ($labels as $label) {
            if (! in_array($label, $unique, true)) {
                $unique[] = $label;
            }
        }

        if ($unique === []) {
            return null;
        }

        if (count($unique) <= 8) {
            return implode(', ', $unique);
        }

        return implode(', ', array_slice($unique, 0, 8)).' +'.(count($unique) - 8);
    }

    /**
     * @return list<string>
     */
    private function columns(string $table): array
    {
        return $this->tables->columns($table);
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $candidates
     */
    /**
     * Link clicks are the clicks that reached the landing page. The clicks
     * column also counts reactions, comments, and other non-link clicks.
     *
     * @param  list<string>  $columns
     */
    private function clickColumn(array $columns): ?string
    {
        return $this->pick($columns, ['link_clicks', 'clicks']);
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $candidates
     */
    private function pick(array $columns, array $candidates): ?string
    {
        foreach ($candidates as $candidate) {
            if (in_array($candidate, $columns, true)) {
                return $candidate;
            }
        }

        return null;
    }

    private function value(object $row, string $column): mixed
    {
        return $row->{$column} ?? null;
    }

    private function nullableString(mixed $value): ?string
    {
        if ($value === null) {
            return null;
        }

        $string = trim((string) $value);

        return $string === '' ? null : $string;
    }

    private function nullableFloat(mixed $value): ?float
    {
        if ($value === null || $value === '') {
            return null;
        }

        return (float) $value;
    }
}
