<?php

namespace Shm\ShmSocial;

use Shm\ShmDB\mDB;
use Shm\ShmTypes\StructureType;

class ShmSocialsMigrate
{
    public static function migrate(StructureType $structure, string $socialArrayField)
    {

        $items = $structure->find([
            $socialArrayField => ['$exists' => true]
        ]);

        foreach ($items as $item) {
            $socials = $item[$socialArrayField];
            foreach ($socials as $social) {
                if (!$social['id']) {

                    echo "Social not found: " . $social['id'] . " for item: " . $item['_id'] . "\n";
                    continue;
                }


                //Проверка если есть _id то удаялем
                if (isset($social['_id'])) {
                    unset($social['_id']);
                }


                try {
                    ShmSocials::structure()->_updateOne([
                        'id' => $social['id']
                    ], [
                        '$set' => [
                            ...$social,
                            'owner' => $item['_id'],
                            'ownerCollection' => $structure->collection,
                        ],
                    ], [
                        'upsert' => true
                    ]);
                } catch (\Exception $e) {
                    echo json_encode($social, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
                    echo "Error migrating social: " . $e->getMessage() . "\n";

                    exit;
                }
                echo "Migrated social: " . $social['id'] . " for item: " . $item['_id'] . "\n";
            }
        }
    }
}