<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Model;

use WriteTextAI\WriteTextAI\Model\Api\Keywords;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;

/**
 * Handle Keyword Optimization Model
 *
 * @api
 */
class HandleKeywordOptimization
{
    /**
     * @var Keywords
     */
    protected $keywordsApi;

    /**
     * @var StoreHelper
     */
    protected $storeHelper;

    /**
     * Constructor
     *
     * @param Keywords $keywordsApi
     * @param StoreHelper $storeHelper
     */
    public function __construct(
        Keywords $keywordsApi,
        StoreHelper $storeHelper
    ) {
        $this->keywordsApi = $keywordsApi;
        $this->storeHelper = $storeHelper;
    }

    /**
     * Delete keyword optimizations for given record IDs across all stores
     *
     * @param array $recordIds Array of record IDs to delete optimizations for
     * @param string $type Entity type (default: 'Product')
     * @return array Results of deletion operations
     */
    public function deleteKeywordOptimizations(array $recordIds, string $type = 'Product'): array
    {
        $results = [];
        $stores = $this->storeHelper->getAllStores(true);

        foreach ($stores as $store) {
            $storeId = $store->getId();
            $storeResults = [
                'store_id' => $storeId,
                'store_name' => $store->getName(),
                'deleted_count' => 0,
                'errors' => []
            ];

            try {
                // Get optimization list for this store
                $optimizationList = $this->keywordsApi->getOptimizationList(
                    $storeId,
                    [], // status - empty array to get all statuses
                    null, // token
                    $type,
                    $recordIds // specific record IDs
                );

                // Check if there are results to delete
                if (!empty($optimizationList['result'])) {
                    foreach ($optimizationList['result'] as $optimization) {
                        try {
                            // Delete the optimization
                            $this->keywordsApi->deleteOptimization(
                                $storeId,
                                $optimization['recordId'],
                                $type
                            );
                            $storeResults['deleted_count']++;
                        } catch (\Exception $e) {
                            $storeResults['errors'][] = [
                                'record_id' => $optimization['recordId'] ?? $optimization['id'],
                                'error' => $e->getMessage()
                            ];
                        }
                    }
                }
            } catch (\Exception $e) {
                $storeResults['errors'][] = [
                    'record_id' => 'store_level',
                    'error' => $e->getMessage()
                ];
            }

            $results[] = $storeResults;
        }

        return $results;
    }
}
