<?php

namespace Meliconnect\Meliconnect\Modules\Exporter\Services;

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

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Helpers\MeliconMeli;
use Meliconnect\Meliconnect\Core\Models\Template;
use Meliconnect\Meliconnect\Core\Models\UserConnection;
use Meliconnect\Meliconnect\Modules\Exporter\Models\ProductToExport;
use Meliconnect\Meliconnect\Modules\Exporter\Services\MercadoLibreListingAdapter;

/**
 * Orchestrates the process of obtaining transformed product data from
 * the MercadoLibreListingAdapter and creating or updating products in
 * WooCommerce.
 */

class ListingDataFacade
{

    protected $mercadoLibreListingAdapter;

    public function __construct(
        MercadoLibreListingAdapter $mercadoLibreListingAdapter,
    ) {
        $this->mercadoLibreListingAdapter = $mercadoLibreListingAdapter;
    }

    public function getAndExportListing($meli_user_id, $woo_product_id, $template_id, $meliListingId = null, $sync_options = null)
    {
        $meli_user_data = UserConnection::getUser($meli_user_id);

        if (! $meli_user_data) {
            Helper::logData('User not found: ' . $meli_user_id, 'custom-export');
            return false;
        }

        // Obtener datos transformados desde el servidor usando el adaptador
        $exportedResponse = $this->mercadoLibreListingAdapter->getTransformedListingData($meli_user_data, $woo_product_id, $template_id, $meliListingId, $sync_options);



        if ((! isset($exportedResponse['status']) || $exportedResponse['status'] !== 200 || ! isset($exportedResponse['data']) || empty($exportedResponse['data']))) {
            Helper::logData('Hub error exporting listing data: ' . wp_json_encode($exportedResponse), 'custom-export');

            // Mensaje amigable para el usuario
            $error_message = array(
                'hub_error' => 'There was an issue communicating with the Meliconnect server. Please try again. If the problem persists, contact support via private message and include the last exported JSON data.'
            );

            // Guardar estado en tabla
            ProductToExport::update_product_to_export_status(
                $woo_product_id,
                'failed',
                $error_message
            );

            // Guardar error en meta (para mostrar en UI)
            update_post_meta(
                $woo_product_id,
                'meliconnect_export_meli_errors',
                maybe_serialize($error_message)
            );

            update_post_meta(
                $woo_product_id,
                'meliconnect_export_meli_error_time',
                time()
            );

            return false;
        } else {
            //Helper::logData('Exported listing data: ' . wp_json_encode($exportedResponse), 'custom-export');
        }

        $this->processExportedResponse($exportedResponse, $woo_product_id);

        return $exportedResponse;
    }




    private function processExportedResponse($exportedResponse, $woo_product_id)
    {
        if (! isset($exportedResponse['data']) || empty($exportedResponse['data'])) {
            return; // Si no hay datos, salimos del método
        }

        // Array para almacenar todos los errores
        $all_errors = array();

        foreach ($exportedResponse['data'] as $listing) {

            $item_errors        = $this->processItemResponse($woo_product_id, $listing['item']);
            $description_errors = $this->processDescriptionResponse($woo_product_id, $listing['description']);


            // Acumular errores si existen
            if ($item_errors) {
                Helper::logData('ITEM errors: ' . wp_json_encode($item_errors), 'custom-export');
                $all_errors['item'] = $item_errors;
            }

            if ($description_errors) {
                Helper::logData('DESCRIPTION errors: ' . wp_json_encode($description_errors), 'custom-export');
                $all_errors['description'] = $description_errors;
            }
        }


        update_post_meta($woo_product_id, 'meliconnect_last_export_time', time());

        // Si hay errores, almacenarlos en un array serializado en la base de datos
        if (!empty($all_errors)) {
            //Helper::logData('Updating errors: ' . var_export($all_errors,true), 'custom-export');

            ProductToExport::update_product_to_export_status($woo_product_id, 'failed', $all_errors);
            
            update_post_meta($woo_product_id, 'meliconnect_export_meli_errors', maybe_serialize($all_errors));
            update_post_meta($woo_product_id, 'meliconnect_export_meli_error_time', time());
        } else {
            ProductToExport::update_product_to_export_status($woo_product_id, 'finished', '');
            // Si no hay errores, eliminamos el campo de errores previo
            delete_post_meta($woo_product_id, 'meliconnect_export_meli_errors');
            delete_post_meta($woo_product_id, 'meliconnect_export_meli_error_time');
        }
    }

    private function processItemResponse($woo_product_id, $response)
    {
        // Caso éxito
        if (!empty($response['success'])) {

            $body = $response['body'] ?? [];

            $listing_id = $body['id'] ?? null;
            $permalink  = $body['permalink'] ?? null;
            $seller_id  = $body['seller_id'] ?? null;

            delete_post_meta($woo_product_id, 'meliconnect_export_meli_errors');
            delete_post_meta($woo_product_id, 'meliconnect_export_meli_error_time');

            ProductToExport::mark_as_finished_with_listing_data(
                $woo_product_id,
                $listing_id,
                $permalink,
                $seller_id
            );

            $this->updateProductMetas($woo_product_id, $response);

            return null;
        }

        // Caso error
        $errors   = [];
        $warnings = [];

        //Helper::logData('ITEM response: ' . wp_json_encode($response), 'custom-export');

        // Parsear cause si existe
        if (!empty($response['body']['cause']) && is_array($response['body']['cause'])) {

            foreach ($response['body']['cause'] as $cause) {

                if (!empty($cause['type']) && $cause['type'] === 'error') {
                    $errors[] = $cause['message'] ?? 'Unknown error';
                }

                if (!empty($cause['type']) && $cause['type'] === 'warning') {
                    $warnings[] = $cause['message'] ?? 'Unknown warning';
                }
            }
        }

        // allback si no vino cause
        if (empty($errors) && !empty($response['errors'])) {

            $errors[] = is_array($response['errors'])
                ? implode(', ', $response['errors'])
                : $response['errors'];
        }

        // log de warnings (no rompen flujo)
        if (!empty($warnings)) {
            //Helper::logData('ITEM warnings: ' . wp_json_encode($warnings), 'custom-export');
        }

        return !empty($errors) ? $errors : null;
    }

    private function processDescriptionResponse($woo_product_id, $response)
    {

        //Helper::logData('DESCRIPTION response: ' . wp_json_encode($response));

        if ($response['success'] === true) {

            ProductToExport::update_product_to_export_status(
                $woo_product_id,
                'finished',
                ''
            );

            return null;
        }

        return $response['errors'] ?? ['Unknown error'];
    }





    private function updateProductMetas($woo_product_id, $listing_item)
    {

        $listing_item = $listing_item['body'];
        //Helper::logData( 'listing_item: ' . wp_json_encode( $listing_item ) );

        update_post_meta($woo_product_id, 'meliconnect_meli_seller_id', $listing_item['seller_id']);
        update_post_meta($woo_product_id, 'meliconnect_meli_category_id', $listing_item['category_id']);
        update_post_meta($woo_product_id, 'meliconnect_meli_listing_id', $listing_item['id']);
        update_post_meta($woo_product_id, 'meliconnect_meli_permalink', $listing_item['permalink']);
        update_post_meta($woo_product_id, 'meliconnect_meli_listing_type_id', $listing_item['listing_type_id']);
        update_post_meta($woo_product_id, 'meliconnect_meli_user_product_id', $listing_item['user_product_id'] ?? null);

        update_post_meta($woo_product_id, 'meliconnect_meli_status', $listing_item['status']);
        update_post_meta($woo_product_id, 'meliconnect_meli_sub_status', $listing_item['sub_status']);
        update_post_meta($woo_product_id, 'meliconnect_meli_site_id', $listing_item['site_id']);
        update_post_meta($woo_product_id, 'meliconnect_meli_catalog_product_id', $listing_item['catalog_product_id']);
        update_post_meta($woo_product_id, 'meliconnect_meli_domain_id', $listing_item['domain_id']);
        update_post_meta($woo_product_id, 'meliconnect_meli_sold_quantity', $listing_item['sold_quantity']);
        update_post_meta($woo_product_id, 'meliconnect_meli_shipping_mode', $listing_item['shipping']['mode']);
    }
}
