<?php

namespace Meliconnect\Meliconnect\Core\Helpers;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

use Meliconnect\Meliconnect\Core\Helpers\Helper;

class SyncHashHelper
{
    private static $log_channel = 'sync-cron';

    public static function normalizeMeliItem($meli, $variation = null)
    {
        $source = $variation ?: $meli;

        return [
            'id' => $meli->id ?? null,

            'variation_id' => $variation->id ?? null,

            'price' => (float) ($source->price ?? 0),

            'available_quantity' => (int) (
                $source->available_quantity
                ?? $meli->available_quantity
                ?? 0
            ),

            'status' => strtolower(
                trim($source->status ?? $meli->status ?? 'paused')
            ),

            'last_updated' => $meli->last_updated ?? null,
        ];
    }




    public static function buildHashFromMeli($meli, $type = 'full', $changes = [])
    {
        return self::buildHash([
            'price' => number_format(
                (float) ($meli['price'] ?? 0),
                2,
                '.',
                ''
            ),

            'stock' => (int) ($meli['available_quantity'] ?? 0),

            'status' => strtolower(
                trim($meli['status'] ?? 'paused')
            ),

        ], $type, $changes, 'meli');
    }

    public static function buildHashFromWoo($woo, $type = 'full', $changes = [])
    {
        return self::buildHash([
            'price' => number_format(
                (float) $woo->get_price(),
                2,
                '.',
                ''
            ),

            'stock' => (int) $woo->get_stock_quantity(),

            'status' => strtolower(
                trim(
                    self::mapStatus($woo->get_status())
                )
            ),

        ], $type, $changes, 'woo');
    }

    private static function buildHash(array $data, $type = 'full', $changes = [], $source = '')
    {
        $fields = [
            'price',
            'stock',
            'status'
        ];

        // ===============================
        // PARTIAL HASH
        // ===============================
        if (!empty($changes)) {

            $parts = [];

            foreach ($fields as $field) {

                if (!empty($changes[$field])) {
                    $parts[] = "{$field}:{$data[$field]}";
                }
            }

            $base_string = implode('|', $parts);
        } else {

            // ===============================
            // LEGACY / FULL
            // ===============================
            $base_string = match ($type) {

                'price'  => $data['price'],
                'stock'  => $data['stock'],
                'status' => $data['status'],

                'full'   => implode('|', [
                    $data['price'],
                    $data['stock'],
                    $data['status']
                ]),

                default  => implode('|', [
                    $data['price'],
                    $data['stock'],
                    $data['status']
                ]),
            };
        }

        $hash = md5($base_string);

        /* Helper::logData(
            strtoupper($source) .
                " HASH [type={$type}] changes=" .
                json_encode($changes) .
                " base='{$base_string}' hash={$hash}",
            self::$log_channel
        ); */

        return $hash;
    }



    public static function mapStatus($wc_status)
    {
        return match ($wc_status) {
            'publish' => 'active',
            default   => 'paused'
        };
    }

    public static function mapMeliStatus($meli_status)
    {
        return match ($meli_status) {
            'active' => 'publish',
            'paused' => 'draft',
            default  => 'draft'
        };
    }

    public static function resolvePriority($type)
    {
        return match ($type) {
            'stock'  => 1,  // urgent
            'price'  => 5,
            'status' => 8,
            'full'   => 10,
            default  => 15,
        };
    }
}
