<?php

namespace Mtc\Plugins\Wisebee\Classes\Commands;

use Illuminate\Console\Command;
use Mtc\Plugins\Wisebee\Classes\Handlers\TranscriptHandler;
use Mtc\Plugins\Wisebee\Classes\WisebeeManager;
use Wisebee\Resources\Transcription as RemoteTranscription;

class BackfillTranscriptsCommand extends Command
{
    protected $signature = 'wisebee:backfill-transcripts {--limit=100 : Page size when enumerating remote transcripts}';

    protected $description = 'Pulls all historical Wisebee transcripts into the local mirror. Idempotent — safe to re-run.';

    public function handle(): int
    {
        $manager = new WisebeeManager();
        $handler = new TranscriptHandler($manager);
        $wisebee = $manager->wisebee();

        $limit = (int) $this->option('limit');
        $offset = 0;
        $imported = 0;

        while (true) {
            $batch = $wisebee->list(RemoteTranscription::class, [
                'offset' => $offset,
                'limit' => $limit,
            ]);

            if ($batch === false) {
                $this->error('Wisebee API error: ' . $wisebee->getErrorMessage());
                return self::FAILURE;
            }
            if (empty($batch)) {
                break;
            }

            foreach ($batch as $remote) {
                /** @var RemoteTranscription $remote */
                $handler->upsertTranscript($remote);
                $imported++;
            }

            $this->info(sprintf('Processed %d transcripts (offset %d).', count($batch), $offset));

            if (count($batch) < $limit) {
                break;
            }
            $offset += $limit;
        }

        $this->info(sprintf('Backfill complete. %d transcripts upserted.', $imported));
        return self::SUCCESS;
    }
}
