<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Search;

use Numinix\SeekmodoWordPress\LocalIndex\LocalIndexRetriever;
use Numinix\SeekmodoWordPress\LocalIndex\VerticalConfig;

/**
 * Enhanced native WooCommerce product retrieval.
 */
final class WooCommerceRetriever
{
    /**
     * @return array{ids: list<int>, total: int}
     */
    public static function search(string $q, int $page, int $pageSize): array
    {
        if (VerticalConfig::shouldUseLocalIndex('commerce')) {
            return LocalIndexRetriever::searchProducts($q, $page, $pageSize);
        }
        if (!function_exists('wc_get_products')) {
            return ['ids' => [], 'total' => 0];
        }
        $args = [
            'status'  => 'publish',
            'limit'   => $pageSize,
            'page'    => max(1, $page),
            'return'  => 'ids',
            's'       => $q,
            'orderby' => 'meta_value_num',
            'meta_key'=> 'total_sales',
            'order'   => 'DESC',
        ];
        $ids = wc_get_products($args);
        if (!is_array($ids)) {
            return ['ids' => [], 'total' => 0];
        }
        $intIds = array_values(array_filter(array_map('intval', $ids)));

        return ['ids' => $intIds, 'total' => count($intIds)];
    }

    /**
     * @return list<array<string,mixed>>
     */
    public static function typeaheadRows(string $q, int $max): array
    {
        if (VerticalConfig::shouldUseLocalIndex('commerce')) {
            return LocalIndexRetriever::typeaheadRows($q, $max, 'commerce');
        }
        $r = self::search($q, 1, $max);

        return self::rowsFromIds($r['ids'], $max);
    }

    /**
     * @param list<int> $ids
     * @return list<array<string,mixed>>
     */
    public static function rowsFromIds(array $ids, int $max): array
    {
        if (!function_exists('wc_get_product')) {
            return [];
        }
        $out = [];
        foreach ($ids as $id) {
            if (count($out) >= $max) {
                break;
            }
            $product_id = (int) $id;
            if ($product_id <= 0) {
                continue;
            }
            $product = wc_get_product($product_id);
            if (!$product) {
                continue;
            }
            $out[] = [
                'id'         => (string) $product_id,
                'title'      => $product->get_name(),
                'permalink'  => $product->get_permalink(),
                'image_url'  => (string) wp_get_attachment_image_url($product->get_image_id(), 'thumbnail'),
                'price'      => $product->get_price(),
                'in_stock'   => $product->is_in_stock(),
                'sku'        => $product->get_sku(),
            ];
        }

        return $out;
    }
}
