<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Setting;

class RemoveDuplicateSettings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'settings:remove-duplicates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove setting entries that are duplicate. Must be run per tenant';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $settings = Setting::all()
            ->groupBy('config_key')
            ->filter(fn ($group) => $group->count() > 1);


        if ($settings->count()) {
            $this->info($settings->count() . " settings with duplicates: " . $settings->keys()->implode(', '));
            if (!$this->confirm('Do you want to remove the oldest updated one for each of the duplicates?')) {
                $this->info('k, bye');
                return self::SUCCESS;
            }

            $settings->each(function (Collection $groupedSettings) {
                $groupedSettings->sortByDesc('updated_at')
                    ->skip(1)
                    ->each(fn (Setting $setting) => $setting->delete());
            });
        }

        return self::SUCCESS;
    }
}
