<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAdmin\SchemaCollections\ShmExportCollection;
use Shm\ShmAdmin\SchemaCollections\ShmexportsField;
use Shm\ShmAuth\Auth;
use Shm\ShmDB\mDB;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmUtils\I18n;
use Shm\ShmUtils\Response;

class AdminRPCDeleteExport
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::bool(),
                'args' => Shm::structure([
                    "_id" => Shm::ID()->default(null),
                ]),
                'resolve' => function ($root, $args) {

                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);

                    $_id = $args['_id'] ?? null;

                    if (!$_id) {
                        Response::validation(I18n::get('no_data_to_delete'));
                    }

                    $export = ShmExportCollection::findOne([
                        ShmexportsField::_ID => mDB::id($_id)
                    ]);
                    if (!$export) {
                        Response::validation(I18n::get('export_not_found'));
                    }
                    ShmExportCollection::structure()->deleteOne([
                        ShmexportsField::_ID => mDB::id($_id)
                    ]);

                    $filePath = ShmexportsField::FILE_PATH_GET($export);
                    if ($filePath && file_exists($filePath)) {
                        unlink($filePath);
                    }

                    return true;
                }
            ];
        });
    }
}
