<?php

namespace Meliconnect\Meliconnect\Core;

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

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Helpers\MeliconMeli;
use Meliconnect\Meliconnect\Core\Helpers\SyncHashHelper;
use Meliconnect\Meliconnect\Core\Services\SyncContextResolver;

class SyncDirectionResolver
{
    private $log_channel = 'sync-cron';
    private $settings = [];

    public function resolve($item)
    {
        $this->settings = Helper::getMeliconnectOptions('sync');

        $directionMode = $this->settings['meliconnect_sync_direction'] ?? 'woo_to_meli';

        // ===============================
        // PRIMER SYNC
        // ===============================
        if (empty($item->last_hash)) {

            Helper::logData(
                "Resolver: first sync using setting={$directionMode} item {$item->id}",
                $this->log_channel
            );

            return $this->resolveFirstSync($item, $directionMode);
        }

        // ===============================
        // ANTI-REBOTE
        // ===============================
        if (!empty($item->last_sync_at) && strtotime($item->last_sync_at) > time() - 10) {
            Helper::logData("Resolver: debounce skip item {$item->id}", $this->log_channel);
            return null;
        }

        // ===============================
        // CONTEXTO COMPARTIDO
        // ===============================

        $context = SyncContextResolver::build($item, $this->log_channel);

        if (!$context) {
            return null;
        }

        $woo  = $context['woo'];
        $meli = $context['meli'];


        // ===============================
        // CHANGES
        // ===============================
        $changes = json_decode($item->changes, true);

        if (!is_array($changes)) {
            $changes = [];
        }

        // ===============================
        // HASHES
        // ===============================
        $wc_hash   = SyncHashHelper::buildHashFromWoo($woo, $item->sync_type);
        $meli_hash = SyncHashHelper::buildHashFromMeli($meli, $item->sync_type);

         Helper::logData([
            'message' => 'HASH COMPARE',
            'item_id' => $item->id,
            'woo_hash' => $wc_hash,
            'meli_hash' => $meli_hash,
            'last_hash' => $item->last_hash,
        ], $this->log_channel);

        // ===============================
        // DETECCIÓN DIRECCIÓN
        // ===============================
        if ($wc_hash !== $item->last_hash && $meli_hash === $item->last_hash) {
            return 'woo_to_meli';
        }

        if ($meli_hash !== $item->last_hash && $wc_hash === $item->last_hash) {
            return 'meli_to_woo';
        }

        // ===============================
        //  CONFLICTO
        // ===============================
        Helper::logData("CONFLICT detected item {$item->id}", $this->log_channel);

        return $this->resolveConflict($woo, $meli, $item, $directionMode, $changes);
    }



    private function resolveConflict($woo, $meli, $item, $directionMode, $changes)
    {
        // 1. respetar direction global en settings
        if ($directionMode === 'woo_to_meli' || $directionMode === 'meli_to_woo') {
            return $directionMode;
        }

        // 2. respetar source
        if ($item->source === 'meli') {
            Helper::logData("Conflict resolved by source=meli", $this->log_channel);
            return 'meli_to_woo';
        }

        if ($item->source === 'woo') {
            Helper::logData("Conflict resolved by source=woo", $this->log_channel);
            return 'woo_to_meli';
        }

        // 3. fallback a config
        $mode = $this->settings['meliconnect_sync_conflict_resolution'] ?? 'woo';

        return match ($mode) {
            'meli' => 'meli_to_woo',
            'woo'  => 'woo_to_meli',
            'auto' => $this->resolveByDate($woo, $meli),
            default => 'woo_to_meli'
        };
    }

    private function resolveByDate($woo, $meli)
    {
        $wooTime = $woo->get_date_modified()
            ? $woo->get_date_modified()->getTimestamp()
            : 0;

        $meliTime = !empty($meli['last_updated'])
            ? strtotime($meli['last_updated'])
            : 0;

        Helper::logData(
            "Resolve by date → woo={$wooTime} meli={$meliTime}",
            $this->log_channel
        );

        if ($meliTime === $wooTime) {
            return 'woo_to_meli';
        }

        return ($meliTime > $wooTime)
            ? 'meli_to_woo'
            : 'woo_to_meli';
    }



    private function resolveFirstSync($item, $directionMode)
    {
        if ($directionMode === 'woo_to_meli' || $directionMode === 'meli_to_woo') {
            return $directionMode;
        }

        // bidirectional
        $mode = $this->settings['meliconnect_sync_conflict_resolution'] ?? 'woo';

        return match ($mode) {
            'meli' => 'meli_to_woo',
            'woo'  => 'woo_to_meli',
            'auto' => $this->resolveFirstSyncAuto($item),
            default => 'woo_to_meli'
        };
    }

    private function resolveFirstSyncAuto($item)
    {
        $context = SyncContextResolver::build(
            $item,
            $this->log_channel
        );

        if (!$context) {

            Helper::logData(
                "First sync auto fallback → woo_to_meli | item {$item->id}",
                $this->log_channel
            );

            return 'woo_to_meli';
        }

        return $this->resolveByDate(
            $context['woo'],
            $context['meli']
        );
    }
}
