<?php

namespace App\Modules\Leasing\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\KeyloopLeaseColour;
use Mtc\MercuryDataModels\KeyloopLeaseDiscount;
use Mtc\MercuryDataModels\KeyloopLeaseOption;
use Mtc\MercuryDataModels\KeyloopLeaseOptionCategory;
use Mtc\MercuryDataModels\KeyloopLeaseOptionPrice;
use Mtc\MercuryDataModels\KeyloopLeasePriceMapping;
use Mtc\MercuryDataModels\KeyloopLeaseResidualValue;
use Mtc\MercuryDataModels\KeyloopLeaseVariantOptionMapping;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class PurgeOldLeaseDataJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function handle()
    {
        collect([
            KeyloopLeaseColour::class,
            KeyloopLeaseDiscount::class,
            KeyloopLeaseVehicleVariant::class,
            KeyloopLeaseResidualValue::class,
            KeyloopLeaseOption::class,
            KeyloopLeaseOptionPrice::class,
            KeyloopLeaseVariantOptionMapping::class,
            KeyloopLeasePriceMapping::class,
            KeyloopLeaseOptionCategory::class
        ])->each(fn ($class) => $this->purgeData(App::make($class)));
    }

    private function purgeData(Model $model)
    {
        $model::query()
            ->where('was_recently_synced', '=', false)
            ->chunk(100, fn ($collection) => $model::query()->whereIn('id', $collection->pluck('id'))->delete());
    }
}
