<?php
/**
 * Caterpoint Product Import Helper
 *
 * @category    PortalPeople
 * @package     Caterpoint
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\caterpoint\models\import;

use yii\db\ActiveRecord;

/**
 * Helper class for resolving local master products from Caterpoint product codes.
 *
 * Products in the local system store the Caterpoint stock code in their JSON
 * `data` column under the path `$.caterpoint.stock_code`. This class queries
 * that column to find the matching master product record.
 */
class Products
{
    /**
     * Find a master product by its Caterpoint stock code.
     *
     * Queries the products table using MySQL JSON_VALUE to match the Caterpoint
     * stock code stored at json path `$.caterpoint.stock_code` in the `data` column.
     *
     * @param string|int $stockCode The Caterpoint stock code to look up
     * @return ActiveRecord|null The master product model, or null if not found
     */
    public static function findByStockCode(string|int $stockCode): ?ActiveRecord
    {
        return \backend\models\Productsbe::find()
            ->where("JSON_VALUE(data, '$.caterpoint.stock_code') = :code", [':code' => (string) $stockCode])
            ->one();
    }
}
