<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Content;

use Numinix\SeekmodoWordPress\Config\Options;

final class PostTypeRegistry
{
    public static function register(): void
    {
        // No hooks; this class is a pure helper. Methods are filter-overridable
        // so callers don't need to register anything to participate.
    }

    /**
     * Return the post types Seekmodo will index + search. Resolution
     * order:
     *   1. Explicit option (seekmodo_wp_indexable_post_types).
     *   2. Filter `seekmodo_indexable_post_types`.
     *   3. Default: post + page + every public, non-builtin CPT.
     *
     * @return array<int,string>
     */
    public static function indexable(): array
    {
        $option = get_option(Options::OPT_INDEXABLE_TYPES, null);
        if (is_array($option) && !empty($option)) {
            $types = array_values(array_unique(array_filter(array_map('strval', $option))));
        } else {
            $types = self::defaults();
        }

        /** @var array<int,string> $types */
        $types = apply_filters('seekmodo_indexable_post_types', $types);

        // Defensive sanitize: keep only registered, non-empty strings.
        return array_values(array_filter(array_map('strval', $types), static function (string $pt): bool {
            return $pt !== '' && (function_exists('post_type_exists') ? post_type_exists($pt) : true);
        }));
    }

    /**
     * @return array<int,string>
     */
    public static function defaults(): array
    {
        if (!function_exists('get_post_types')) {
            return ['post', 'page'];
        }
        $public_cpts = get_post_types(['public' => true, '_builtin' => false], 'names');
        $base        = ['post', 'page'];
        if (is_array($public_cpts)) {
            $base = array_merge($base, array_values($public_cpts));
        }

        // Always exclude Woo's product types — that's the commerce vertical's job.
        $base = array_diff($base, ['product', 'product_variation']);

        return array_values(array_unique($base));
    }
}
