<?php

namespace App\Console\Commands;

use App\Models\Instrument;
use App\Models\MarketTick;
use App\Models\OptionGreek;
use Illuminate\Console\Command;

class PurgeDummyMarketDataCommand extends Command
{
    protected $signature = 'market:purge-dummy {--all-options : Remove all option instruments (use before first live sync)}';

    protected $description = 'Remove dummy/stale option instruments and ticks';

    public function handle(): int
    {
        if ($this->option('all-options')) {
            $ids = Instrument::query()
                ->where(fn ($q) => $q->where('instrument_kind', 'option')->orWhereNull('instrument_kind'))
                ->where('instrument_kind', '!=', 'index')
                ->pluck('id');
        } else {
            $ids = Instrument::query()
                ->where(function ($q) {
                    $q->where('tradingsymbol', 'like', 'NIFTY20%')
                        ->orWhere('token', 'like', '9%');
                })
                ->where(fn ($q) => $q->where('instrument_kind', 'option')->orWhereNull('instrument_kind'))
                ->pluck('id');
        }

        MarketTick::whereIn('instrument_id', $ids)->delete();
        OptionGreek::whereIn('instrument_id', $ids)->delete();
        $removed = Instrument::whereIn('id', $ids)->delete();

        $this->info("Removed {$removed} option instruments.");

        return self::SUCCESS;
    }
}
