<?php

if (!defined('ABSPATH')) {
    exit;
}

/** Builds a bounded read-only snapshot from WooCommerce's canonical product API. */
final class Aysa_AI_Visibility_Commerce_Snapshot {
    public static function build() {
        if (!function_exists('wc_get_products') || !function_exists('wc_get_product')) {
            return new WP_Error(
                'ai_visibility_commerce_woocommerce_unavailable',
                __('WooCommerce is not active on this site.', 'aysaaiseo')
            );
        }
        $products = wc_get_products(array(
            'status' => 'publish',
            'limit' => 1000,
            'orderby' => 'ID',
            'order' => 'ASC',
            'return' => 'objects',
        ));
        $currency = function_exists('get_woocommerce_currency')
            ? (string) get_woocommerce_currency()
            : '';
        $catalog = array();
        foreach (is_array($products) ? $products : array() as $product) {
            if (!is_object($product) || !is_callable(array($product, 'get_id'))) {
                continue;
            }
            $id = absint($product->get_id());
            $name = sanitize_text_field((string) $product->get_name());
            if (!$id || $name === '') {
                continue;
            }
            $stock_status = sanitize_key((string) $product->get_stock_status());
            $availability = array(
                'instock' => 'in_stock',
                'outofstock' => 'out_of_stock',
                'onbackorder' => 'backorder',
            );
            $gtin = is_callable(array($product, 'get_global_unique_id'))
                ? sanitize_text_field((string) $product->get_global_unique_id())
                : '';
            $catalog[] = array(
                'external_id' => (string) $id,
                'name' => $name,
                'aliases' => array(),
                'canonical_url' => esc_url_raw((string) get_permalink($id)),
                'sku' => sanitize_text_field((string) $product->get_sku()),
                'gtin' => $gtin,
                'mpn' => sanitize_text_field((string) get_post_meta($id, '_mpn', true)),
                'price' => is_numeric($product->get_price()) ? (float) $product->get_price() : null,
                'currency' => $currency,
                'availability' => isset($availability[$stock_status]) ? $availability[$stock_status] : 'unknown',
                // These require independent rendered-page verification. Woo data alone is not proof.
                'product_schema' => false,
                'offer_schema' => false,
                'rendered_schema_verified' => false,
                'price_consistent' => false,
                'availability_consistent' => false,
                'crawlable' => false,
                'rendered' => false,
            );
        }
        if (!$catalog) {
            return new WP_Error(
                'ai_visibility_commerce_catalog_empty',
                __('No published WooCommerce products are available for analysis.', 'aysaaiseo')
            );
        }
        return array(
            'catalog' => $catalog,
            'readiness_context' => array(
                'merchant_policies_verified' => self::published_page((int) get_option('wp_page_for_privacy_policy', 0))
                    && self::published_page((int) get_option('woocommerce_terms_page_id', 0)),
                'shipping_returns_verified' => false,
                'product_feed_verified' => false,
                'purchase_steps_verified' => self::published_page((int) get_option('woocommerce_cart_page_id', 0))
                    && self::published_page((int) get_option('woocommerce_checkout_page_id', 0)),
                'ucp_capability_verified' => false,
                'ucp_capability_evidence' => '',
                'competitor_product_names' => array(),
                'minimum_sample_size' => 5,
            ),
        );
    }

    private static function published_page($post_id) {
        return $post_id > 0 && get_post_status($post_id) === 'publish';
    }
}
