<?php

namespace Modules\SmartStorage\Console;

use Illuminate\Console\Command;
use Modules\SmartStorage\Entities\SsFile;
use Modules\SmartStorage\Entities\SsSetting;

/**
 * Re-indexes files that exist on the active local backend root but have no
 * ss_files row — e.g. files written via App\Media::uploadBase64Image(), which
 * bypasses the Storage facade and so never passes through the smart adapter.
 *
 * Only meaningful for the "local" backend (the one rooted on this server). For
 * cloud backends there is nothing local to scan.
 */
class ReconcileCommand extends Command
{
    protected $signature = 'smart-storage:reconcile {--dry-run : List what would be indexed without writing}';

    protected $description = 'Index local Smart Storage files that bypassed the storage adapter';

    public function handle(): int
    {
        $settings = SsSetting::current();

        if ($settings->active_backend !== 'local') {
            $this->warn("Active backend is '{$settings->active_backend}', not 'local' — nothing to reconcile.");
            return self::SUCCESS;
        }

        $root = rtrim(config('smartstorage.local_root', storage_path('app/smart')), '/\\');
        if (!is_dir($root)) {
            $this->warn("Local root does not exist yet: {$root}");
            return self::SUCCESS;
        }

        $dry = (bool) $this->option('dry-run');
        $indexed = 0;

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS)
        );

        foreach ($iterator as $fileInfo) {
            if (!$fileInfo->isFile()) {
                continue;
            }

            $logical = ltrim(str_replace('\\', '/', substr($fileInfo->getPathname(), strlen($root) + 1)), '/');

            if (SsFile::findByLogicalPath($logical, $settings->business_id)) {
                continue;
            }

            $this->line(($dry ? '[dry] ' : '') . "index: {$logical}");

            if (!$dry) {
                SsFile::create([
                    'business_id'  => $settings->business_id,
                    'logical_path' => $logical,
                    'backend'      => 'local',
                    'backend_path' => $logical,
                    'is_encrypted' => false,
                    'size'         => $fileInfo->getSize(),
                    'stored_size'  => $fileInfo->getSize(),
                ]);
            }
            $indexed++;
        }

        $this->info(($dry ? 'Would index ' : 'Indexed ') . $indexed . ' file(s).');

        return self::SUCCESS;
    }
}
