<?php

namespace App\Campaigns;

use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;

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

    /**
     * Campaign list from arb_adops_campaign_performance and other arb_adops_* tables.
     * ROI rows are not included.
     *
     *
     * @param  list<string>|null  $onlyCampaignIds
     * @return array{
     *     ok: bool,
     *     error?: string,
     *     source?: string,
     *     order?: string,
     *     rank_by?: string,
     *     platform?: ?string,
     *     from?: ?string,
     *     to?: ?string,
     *     date_window_applied?: bool,
     *     campaigns_matched?: int,
     *     campaigns_returned?: int,
     *     total_spent?: float,
     *     campaigns?: list<array<string, mixed>>,
     *     note?: string
     * }
     */
    public function listCampaigns(
        ?string $platform,
        ?string $from,
        ?string $to,
        string $order,
        string $rankBy,
        int $limit,
        ?string $status = null,
        ?string $accountId = null,
        ?float $minSpent = null,
        ?array $onlyCampaignIds = null,
        bool $spendingOnly = false,
    ): array {
        $platform = strtolower(trim((string) $platform));
        $window = $from !== null && $from !== '' && $to !== null && $to !== '';
        $primaryRank = in_array($rankBy, ['sales', 'orders', 'clicks', 'spent', 'cpc'], true) ? $rankBy : 'sales';
        $ranked = in_array($rankBy, ['sales', 'orders', 'clicks', 'spent', 'cpc'], true);

        $profiles = $this->profiles($platform);
        $performance = $this->performanceTotals($from, $to, $window);
        $daily = $window && $from === $to ? $this->dailyDelivery($platform, (string) $from) : null;

        if ($daily !== null) {
            $campaigns = $this->campaignsFromDaily($daily, $profiles, $performance, $platform);
        } else {
            $spend = $this->spendTotals($platform, $from, $to, $window);
            $ids = $this->campaignIds($platform, $profiles, $performance, $spend);
            $campaigns = [];

            foreach ($ids as $id => $rowPlatform) {
                $metrics = $performance[$id] ?? ['sales' => 0.0, 'orders' => 0.0, 'clicks' => 0.0];
                $stats = $spend[$id] ?? ['spent' => 0.0, 'clicks' => 0.0, 'impressions' => 0.0, 'conversions' => 0.0];
                $profile = $profiles[$id] ?? null;

                $name = trim((string) ($profile['name'] ?? ''));

                $campaigns[] = [
                    'campaign_id' => $id,
                    'campaign_name' => $name !== '' ? $name : ('Campaign '.$id),
                    'platform' => $rowPlatform,
                    'account_id' => $profile['account_id'] ?? null,
                    'status' => $profile['status'] ?? null,
                    'effective_status' => $profile['effective_status'] ?? null,
                    'start_time' => $profile['start_time'] ?? null,
                    'spent' => round((float) $stats['spent'], 2),
                    'impressions' => (int) round((float) ($stats['impressions'] ?? 0)),
                    'conversions' => round((float) ($stats['conversions'] ?? 0), 4),
                    'sales' => round((float) $metrics['sales'], 2),
                    'orders' => round((float) $metrics['orders'], 4),
                    'clicks' => round((float) (isset($performance[$id]) ? $metrics['clicks'] : $stats['clicks']), 4),
                ];
            }

            $campaigns = array_values(array_filter(
                $campaigns,
                fn (array $row): bool => trim((string) ($row['start_time'] ?? '')) !== '',
            ));
        }

        $statusFilter = $daily === null ? $this->statusFilter($status) : null;

        if ($statusFilter !== null) {
            $campaigns = array_values(array_filter(
                $campaigns,
                fn (array $row): bool => $this->matchesStatus($row['status'] ?? null, $row['effective_status'] ?? null, $statusFilter),
            ));
        }

        $accountKey = $this->accountKey($accountId);

        if ($accountKey !== '') {
            $campaigns = array_values(array_filter(
                $campaigns,
                fn (array $row): bool => $this->accountKey($row['account_id'] ?? null) === $accountKey,
            ));
        }

        if ($onlyCampaignIds !== null) {
            $allowed = [];

            foreach ($onlyCampaignIds as $id) {
                $allowed[(string) $id] = true;
            }

            $campaigns = array_values(array_filter(
                $campaigns,
                fn (array $row): bool => isset($allowed[(string) $row['campaign_id']]),
            ));
        }

        if ($minSpent !== null) {
            $campaigns = array_values(array_filter(
                $campaigns,
                fn (array $row): bool => (float) $row['spent'] >= $minSpent,
            ));
        }

        foreach ($campaigns as $index => $campaign) {
            $clicks = (float) ($campaign['clicks'] ?? 0);
            $campaigns[$index]['cpc'] = $clicks > 0 ? round((float) $campaign['spent'] / $clicks, 4) : null;
        }

        if ($spendingOnly) {
            $campaigns = array_values(array_filter(
                $campaigns,
                fn (array $row): bool => (float) $row['spent'] > 0,
            ));
        }

        if ($primaryRank === 'cpc') {
            $campaigns = array_values(array_filter(
                $campaigns,
                fn (array $row): bool => (float) ($row['clicks'] ?? 0) > 0 && $row['cpc'] !== null,
            ));
        }

        if ($daily !== null && $order === 'list') {
            usort($campaigns, function (array $left, array $right): int {
                $spent = $right['spent'] <=> $left['spent'];

                if ($spent !== 0) {
                    return $spent;
                }

                return $left['campaign_id'] <=> $right['campaign_id'];
            });
        } else {
            $this->sortCampaigns($campaigns, $order, $primaryRank, $ranked);
        }

        $matched = count($campaigns);
        $returned = array_slice($campaigns, 0, $limit);

        return [
            'ok' => true,
            'source' => 'arb_adops',
            'order' => in_array($order, ['latest', 'old'], true) ? $order : ($ranked ? $order : 'list'),
            'rank_by' => $primaryRank,
            'platform' => $platform !== '' ? $platform : null,
            'from' => $window ? $from : null,
            'to' => $window ? $to : null,
            'date_window_applied' => $window,
            'daily_stats' => $daily !== null,
            'campaigns_matched' => $matched,
            'campaigns_returned' => count($returned),
            'total_spent' => round(array_sum(array_column($campaigns, 'spent')), 2),
            'campaigns' => $returned,
            'note' => 'Main list is Whale arb_adops_campaign_performance and other arb_adops_* tables. Sales are net_revenue. Spent is platform spend. ROI is not included here.',
        ];
    }

    /**
     * @param  list<array<string, mixed>>  $campaigns
     */
    private function sortCampaigns(array &$campaigns, string $order, string $primaryRank, bool $ranked): void
    {
        usort($campaigns, function (array $left, array $right) use ($order, $primaryRank, $ranked): int {
            if ($order === 'latest' || $order === 'old') {
                return $this->compareStartTime($left, $right, $order === 'latest');
            }

            if (! $ranked || $order === 'list') {
                return [$left['platform'], $left['campaign_name'], $left['campaign_id']]
                    <=> [$right['platform'], $right['campaign_name'], $right['campaign_id']];
            }

            if ($primaryRank === 'cpc') {
                $compared = ($left['cpc'] ?? PHP_FLOAT_MAX) <=> ($right['cpc'] ?? PHP_FLOAT_MAX);

                if ($order === 'worst') {
                    $compared = -$compared;
                }
            } else {
                $compared = $left[$primaryRank] <=> $right[$primaryRank];

                if ($order === 'top') {
                    $compared = -$compared;
                }
            }

            if ($compared !== 0) {
                return $compared;
            }

            $spent = $right['spent'] <=> $left['spent'];

            if ($spent !== 0) {
                return $spent;
            }

            return $left['campaign_id'] <=> $right['campaign_id'];
        });
    }

    /**
     * Campaigns with a row in arb_adops_stats_daily_YYYYMM on this date.
     * Ad rows are summed to one total per campaign.
     *
     * @return array<string, array{spent: float, impressions: float, clicks: float, account_id: ?string}>
     */
    private function dailyDelivery(string $platform, string $date): array
    {
        $totals = [];

        foreach ($this->tables->tablesFor('stats_daily', $date, $date) as $table) {
            $columns = $this->tables->columns($table);
            $idColumn = $this->column($columns, ['campaign_id', 'external_campaign_id']);
            $dateColumn = $this->column($columns, ['stat_date', 'date']);
            $spendColumn = $this->column($columns, ['spend', 'cost']);

            if ($idColumn === null || $dateColumn === null || $spendColumn === null) {
                continue;
            }

            $platformColumn = $this->column($columns, ['platform']);
            $clicksColumn = $this->column($columns, ['clicks']);
            $impressionsColumn = $this->column($columns, ['impressions']);
            $accountColumn = $this->column($columns, ['account_id', 'ad_account_id']);
            $query = DB::connection('whale')->table($table)
                ->select($idColumn)
                ->selectRaw('SUM('.$spendColumn.') as spent')
                ->selectRaw($clicksColumn !== null ? 'SUM('.$clicksColumn.') as clicks' : '0 as clicks')
                ->selectRaw($impressionsColumn !== null ? 'SUM('.$impressionsColumn.') as impressions' : '0 as impressions')
                ->selectRaw($accountColumn !== null ? 'MAX('.$accountColumn.') as account_id' : 'NULL as account_id')
                ->whereBetween($dateColumn, [$date, $date])
                ->groupBy($idColumn);
            $this->wherePlatform($query, $platformColumn, $platform);

            try {
                foreach ($query->get() as $row) {
                    $id = trim((string) ($row->{$idColumn} ?? ''));

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

                    $current = $totals[$id] ?? ['spent' => 0.0, 'impressions' => 0.0, 'clicks' => 0.0, 'account_id' => null];
                    $accountId = $this->nullableString($row->account_id ?? null);
                    $totals[$id] = [
                        'spent' => $current['spent'] + (float) $row->spent,
                        'impressions' => $current['impressions'] + (float) $row->impressions,
                        'clicks' => $current['clicks'] + (float) $row->clicks,
                        'account_id' => $current['account_id'] ?? $accountId,
                    ];
                }
            } catch (Throwable) {
                continue;
            }
        }

        return $totals;
    }

    /**
     * @param  array<string, array{spent: float, impressions: float, clicks: float, account_id: ?string}>  $daily
     * @param  array<string, array{name: string, platform: string, account_id: ?string, status: ?string, effective_status: ?string, start_time: ?string}>  $profiles
     * @param  array<string, array{sales: float, orders: float, clicks: float}>  $performance
     * @return list<array<string, mixed>>
     */
    private function campaignsFromDaily(array $daily, array $profiles, array $performance, string $platform): array
    {
        $campaigns = [];

        foreach ($daily as $id => $stats) {
            $profile = $profiles[$id] ?? null;
            $metrics = $performance[$id] ?? ['sales' => 0.0, 'orders' => 0.0, 'clicks' => 0.0];
            $name = trim((string) ($profile['name'] ?? ''));

            $campaigns[] = [
                'campaign_id' => $id,
                'campaign_name' => $name !== '' ? $name : ('Campaign '.$id),
                'platform' => ($profile['platform'] ?? '') !== '' ? $profile['platform'] : ($platform !== '' ? $platform : 'meta'),
                'account_id' => $stats['account_id'] ?? ($profile['account_id'] ?? null),
                'status' => $profile['status'] ?? null,
                'effective_status' => $profile['effective_status'] ?? null,
                'start_time' => $profile['start_time'] ?? null,
                'spent' => round((float) $stats['spent'], 2),
                'impressions' => (int) round((float) $stats['impressions']),
                'clicks' => round((float) $stats['clicks'], 4),
                'sales' => round((float) $metrics['sales'], 2),
                'orders' => round((float) $metrics['orders'], 4),
            ];
        }

        return $campaigns;
    }

    /**
     * @return list<array{account_id: string, name: ?string, status: ?string, currency: ?string}>
     */
    public function findAccounts(?string $accountId, ?string $name, ?string $platform = null): array
    {
        $accountId = $this->nullableString($accountId);
        $name = $this->nullableString($name);
        $platform = strtolower(trim((string) $platform));

        if ($accountId === null && $name === null) {
            return [];
        }

        $rows = $this->accountRows($platform);

        if ($accountId !== null) {
            $wanted = $this->accountKey($accountId);

            foreach ($rows as $row) {
                if ($this->accountKey($row['account_id']) === $wanted) {
                    return [$row];
                }
            }

            return [[
                'account_id' => $accountId,
                'name' => null,
                'status' => null,
                'currency' => null,
            ]];
        }

        $exact = array_values(array_filter(
            $rows,
            fn (array $row): bool => strcasecmp((string) $row['name'], (string) $name) === 0,
        ));

        if ($exact !== []) {
            return $exact;
        }

        $needle = strtolower((string) $name);

        return array_slice(array_values(array_filter(
            $rows,
            fn (array $row): bool => str_contains(strtolower((string) $row['name']), $needle),
        )), 0, 10);
    }

    /**
     * @return list<array{account_id: string, name: ?string, status: ?string, currency: ?string}>
     */
    private function accountRows(string $platform): array
    {
        $table = $this->tables->name('accounts');

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

        $columns = $this->tables->columns($table);
        $idColumn = $this->column($columns, ['account_id', 'ad_account_id']);

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

        $platformColumn = $this->column($columns, ['platform']);
        $nameColumn = $this->column($columns, ['name', 'account_name']);
        $statusColumn = $this->column($columns, ['status', 'account_status']);
        $currencyColumn = $this->column($columns, ['currency']);
        $query = DB::connection('whale')->table($table);

        $this->wherePlatform($query, $platformColumn, $platform);

        $rows = [];

        try {
            foreach ($query->get() as $row) {
                $id = $this->nullableString($row->{$idColumn} ?? null);

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

                $rows[] = [
                    'account_id' => $id,
                    'name' => $nameColumn !== null ? $this->nullableString($row->{$nameColumn} ?? null) : null,
                    'status' => $statusColumn !== null ? $this->nullableString($row->{$statusColumn} ?? null) : null,
                    'currency' => $currencyColumn !== null ? $this->nullableString($row->{$currencyColumn} ?? null) : null,
                ];
            }
        } catch (Throwable) {
            return [];
        }

        return $rows;
    }

    private function accountKey(mixed $accountId): string
    {
        $accountId = strtolower(trim((string) $accountId));

        if (str_starts_with($accountId, 'act_')) {
            return substr($accountId, 4);
        }

        return $accountId;
    }

    /**
     * @return array<string, array{name: string, platform: string, account_id: ?string, status: ?string, effective_status: ?string, start_time: ?string}>
     */
    private function profiles(string $platform): array
    {
        if (! Schema::connection('whale')->hasTable('arb_adops_campaigns')) {
            return [];
        }

        $columns = $this->tables->columns('arb_adops_campaigns');
        $idColumn = $this->column($columns, ['campaign_id', 'external_campaign_id']);

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

        $platformColumn = $this->column($columns, ['platform']);
        $nameColumn = $this->column($columns, ['name', 'campaign_name']);
        $accountColumn = $this->column($columns, ['account_id', 'ad_account_id']);
        $statusColumn = $this->column($columns, ['status']);
        $effectiveColumn = $this->column($columns, ['effective_status', 'serving_status', 'platform_status']);
        $startColumn = $this->column($columns, ['start_time']);
        $query = DB::connection('whale')->table('arb_adops_campaigns');

        $this->wherePlatform($query, $platformColumn, $platform);

        $profiles = [];

        try {
            foreach ($query->get() as $row) {
                $id = trim((string) ($row->{$idColumn} ?? ''));

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

                $profiles[$id] = [
                    'name' => trim((string) ($nameColumn !== null ? ($row->{$nameColumn} ?? '') : '')),
                    'platform' => strtolower((string) ($platformColumn !== null ? ($row->{$platformColumn} ?? '') : '')),
                    'account_id' => $accountColumn !== null ? $this->nullableString($row->{$accountColumn} ?? null) : null,
                    'status' => $statusColumn !== null ? $this->nullableString($row->{$statusColumn} ?? null) : null,
                    'effective_status' => $effectiveColumn !== null ? $this->nullableString($row->{$effectiveColumn} ?? null) : null,
                    'start_time' => $startColumn !== null ? $this->nullableString($row->{$startColumn} ?? null) : null,
                ];
            }
        } catch (Throwable) {
            return [];
        }

        return $profiles;
    }

    /**
     * @return array<string, array{sales: float, orders: float, clicks: float}>
     */
    private function performanceTotals(?string $from, ?string $to, bool $window): array
    {
        if (! Schema::connection('whale')->hasTable('arb_adops_campaign_performance')) {
            return [];
        }

        $query = DB::connection('whale')
            ->table('arb_adops_campaign_performance')
            ->select('campaign_id')
            ->selectRaw('COALESCE(SUM(net_revenue), 0) as sales')
            ->selectRaw('COALESCE(SUM(orders), 0) as orders')
            ->selectRaw('COALESCE(SUM(clicks), 0) as clicks')
            ->groupBy('campaign_id');

        if ($window) {
            $query->whereBetween('date', [$from, $to]);
        }

        $totals = [];

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

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

                $totals[$id] = [
                    'sales' => (float) $row->sales,
                    'orders' => (float) $row->orders,
                    'clicks' => (float) $row->clicks,
                ];
            }
        } catch (Throwable) {
            return [];
        }

        return $totals;
    }

    /**
     * @return array<string, array{spent: float, clicks: float, impressions: float, conversions: float}>
     */
    private function spendTotals(string $platform, ?string $from, ?string $to, bool $window): array
    {
        $start = $window ? (string) $from : '2000-01-01';
        $end = $window ? (string) $to : '2100-01-01';
        $tables = $this->tables->tablesFor('campaign_daily', $start, $end);

        if ($tables === []) {
            $tables = $this->tables->tablesFor('stats_daily', $start, $end);
        }

        $totals = [];

        foreach ($tables as $table) {
            $columns = $this->tables->columns($table);
            $idColumn = $this->column($columns, ['campaign_id', 'external_campaign_id']);
            $dateColumn = $this->column($columns, ['stat_date', 'date']);
            $spendColumn = $this->column($columns, ['spend', 'cost']);

            if ($idColumn === null || $spendColumn === null) {
                continue;
            }

            $platformColumn = $this->column($columns, ['platform']);
            $clicksColumn = $this->column($columns, ['clicks']);
            $impressionColumn = $this->column($columns, ['impressions']);
            $conversionColumn = $this->column($columns, ['conversions']);
            $query = DB::connection('whale')->table($table)
                ->select($idColumn)
                ->selectRaw('SUM('.$spendColumn.') as spent')
                ->selectRaw($clicksColumn !== null ? 'SUM('.$clicksColumn.') as clicks' : '0 as clicks')
                ->selectRaw($impressionColumn !== null ? 'SUM('.$impressionColumn.') as impressions' : '0 as impressions')
                ->selectRaw($conversionColumn !== null ? 'SUM('.$conversionColumn.') as conversions' : '0 as conversions')
                ->groupBy($idColumn);

            if ($window && $dateColumn !== null) {
                $query->whereBetween($dateColumn, [$from, $to]);
            }

            $this->wherePlatform($query, $platformColumn, $platform);

            try {
                foreach ($query->get() as $row) {
                    $id = trim((string) ($row->{$idColumn} ?? ''));

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

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

        return $totals;
    }

    /**
     * @param  array<string, array{name: string, platform: string, account_id: ?string, status: ?string, effective_status: ?string, start_time: ?string}>  $profiles
     * @param  array<string, array{sales: float, orders: float, clicks: float}>  $performance
     * @param  array<string, array{spent: float, clicks: float, impressions: float, conversions: float}>  $spend
     * @return array<string, string>
     */
    private function campaignIds(string $platform, array $profiles, array $performance, array $spend): array
    {
        $ids = [];

        foreach ($profiles as $id => $profile) {
            $rowPlatform = $profile['platform'] !== '' ? $profile['platform'] : ($platform !== '' ? $platform : 'meta');

            if ($platform !== '' && $rowPlatform !== $platform) {
                continue;
            }

            $ids[$id] = $rowPlatform;
        }

        if ($platform === '' || $platform === 'meta') {
            foreach (array_keys($performance) as $id) {
                $ids[$id] ??= 'meta';
            }
        }

        foreach (array_keys($spend) as $id) {
            $ids[$id] ??= ($platform !== '' ? $platform : 'meta');
        }

        foreach ($this->tables->allAdopsTables() as $table) {
            if ($table === 'arb_adops_campaign_performance') {
                continue;
            }

            $columns = $this->tables->columns($table);
            $idColumn = $this->column($columns, ['campaign_id', 'external_campaign_id']);

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

            $platformColumn = $this->column($columns, ['platform']);
            $query = DB::connection('whale')->table($table)->select($idColumn);

            if ($platformColumn !== null) {
                $query->addSelect($platformColumn);

                $this->wherePlatform($query, $platformColumn, $platform);
            } elseif ($platform !== '' && $platform !== 'meta') {
                continue;
            }

            try {
                foreach ($query->distinct()->get() as $row) {
                    $id = trim((string) ($row->{$idColumn} ?? ''));

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

                    $rowPlatform = strtolower(trim((string) ($platformColumn !== null ? ($row->{$platformColumn} ?? '') : '')));
                    $ids[$id] ??= $rowPlatform !== '' ? $rowPlatform : ($platform !== '' ? $platform : 'meta');
                }
            } catch (Throwable) {
                continue;
            }
        }

        return $ids;
    }

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

        return null;
    }

    /**
     * @param  array{start_time?: ?string, platform: string, campaign_name: string, campaign_id: string}  $left
     * @param  array{start_time?: ?string, platform: string, campaign_name: string, campaign_id: string}  $right
     */
    private function compareStartTime(array $left, array $right, bool $newestFirst): int
    {
        $leftTime = $this->startTimeKey($left['start_time'] ?? null);
        $rightTime = $this->startTimeKey($right['start_time'] ?? null);

        if ($leftTime === null && $rightTime === null) {
            return [$left['platform'], $left['campaign_name'], $left['campaign_id']]
                <=> [$right['platform'], $right['campaign_name'], $right['campaign_id']];
        }

        if ($leftTime === null) {
            return 1;
        }

        if ($rightTime === null) {
            return -1;
        }

        $compared = $leftTime <=> $rightTime;

        if ($newestFirst) {
            $compared = -$compared;
        }

        if ($compared !== 0) {
            return $compared;
        }

        return $left['campaign_id'] <=> $right['campaign_id'];
    }

    private function startTimeKey(?string $value): ?string
    {
        $value = trim((string) $value);

        if ($value === '') {
            return null;
        }

        if (ctype_digit($value)) {
            return Carbon::createFromTimestamp((int) $value)->format('Y-m-d H:i:s');
        }

        try {
            return Carbon::parse($value)->format('Y-m-d H:i:s');
        } catch (Throwable) {
            return $value;
        }
    }

    private function statusFilter(?string $status): ?string
    {
        $status = strtolower(trim((string) $status));

        if (in_array($status, ['active', 'running', 'live'], true)) {
            return 'active';
        }

        if (in_array($status, ['paused', 'pause'], true)) {
            return 'paused';
        }

        return null;
    }

    private function matchesStatus(?string $status, ?string $effectiveStatus, string $filter): bool
    {
        $status = strtoupper(trim((string) $status));
        $effectiveStatus = strtoupper(trim((string) $effectiveStatus));

        if ($filter === 'paused') {
            if ($effectiveStatus !== '') {
                return str_contains($effectiveStatus, 'PAUSED');
            }

            return $status === 'PAUSED';
        }

        $active = ['ACTIVE', 'ENABLED'];

        if ($effectiveStatus !== '') {
            return in_array($effectiveStatus, $active, true);
        }

        return in_array($status, $active, true);
    }

    private function wherePlatform(Builder $query, ?string $column, string $platform): void
    {
        if ($platform === '' || $column === null) {
            return;
        }

        $query->whereRaw('LOWER('.$column.') = ?', [$platform]);
    }

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

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

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