<?php

namespace App\Campaigns;

/**
 * The audience already saved on an ad set. Names come from that row only.
 */
class CampaignAudienceFacts
{
    /**
     * @param  list<array<string, mixed>>  $rows
     * @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 static function fromRows(array $rows): array
    {
        $countries = [];
        $interests = [];
        $jobs = [];
        $ageMin = null;
        $ageMax = null;
        $advantage = false;
        $custom = false;

        foreach ($rows as $row) {
            if (! is_array($row)) {
                continue;
            }

            $countries = [...$countries, ...self::stringList($row['countries'] ?? null)];
            $ageMin = self::age($row['age_min'] ?? null) ?? $ageMin;
            $ageMax = self::age($row['age_max'] ?? null) ?? $ageMax;
            $advantage = $advantage || self::flag($row['advantage_audience'] ?? null);
            $custom = $custom || self::stringList($row['audiences_included'] ?? null) !== [];

            $spec = self::decoded($row['interests'] ?? null);

            foreach (is_array($spec) ? ($spec['flexible_spec'] ?? [$spec]) : [] as $group) {
                if (! is_array($group)) {
                    continue;
                }

                $interests = [...$interests, ...self::names($group['interests'] ?? null)];
                $jobs = [...$jobs, ...self::names($group['work_positions'] ?? null)];
            }
        }

        return [
            'countries' => array_slice(array_values(array_unique($countries)), 0, 3),
            'age_min' => $ageMin,
            'age_max' => $ageMax,
            'interests' => array_slice(array_values(array_unique($interests)), 0, 8),
            'job_titles' => array_slice(array_values(array_unique($jobs)), 0, 8),
            'advantage_audience' => $advantage,
            'custom_audience' => $custom,
        ];
    }

    private static function age(mixed $value): ?int
    {
        if (! is_numeric($value)) {
            return null;
        }

        $age = (int) $value;

        return $age > 0 ? $age : null;
    }

    private static function flag(mixed $value): bool
    {
        return $value === true || $value === 1 || $value === '1';
    }

    /**
     * @return list<string>
     */
    private static function stringList(mixed $value): array
    {
        $decoded = self::decoded($value);

        if (is_string($decoded) && trim($decoded) !== '') {
            return [trim($decoded)];
        }

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

        $names = [];

        foreach ($decoded as $item) {
            if (is_string($item) && trim($item) !== '') {
                $names[] = trim($item);
            } elseif (is_array($item) && is_string($item['name'] ?? null) && trim($item['name']) !== '') {
                $names[] = trim($item['name']);
            }
        }

        return $names;
    }

    /**
     * @return list<string>
     */
    private static function names(mixed $value): array
    {
        return self::stringList($value);
    }

    private static function decoded(mixed $value): mixed
    {
        if (! is_string($value)) {
            return $value;
        }

        $decoded = json_decode($value, true);

        return json_last_error() === JSON_ERROR_NONE ? $decoded : $value;
    }
}
