<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Models\Organization;
use App\Models\Bank;
use App\Models\Admin;
use Illuminate\Console\Command;

class CleanCyclosProfiles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'profiles:clean-about';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clean empty Cyclos migration paragraph markup from profile about fields';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting cleanup of Cyclos migration empty about fields...');
        $this->newLine();

        $totalCleaned = 0;

        // Clean Users
        $usersCleaned = $this->cleanProfileAbout(User::class, 'Users');
        $totalCleaned += $usersCleaned;

        // Clean Organizations
        $organizationsCleaned = $this->cleanProfileAbout(Organization::class, 'Organizations');
        $totalCleaned += $organizationsCleaned;

        // Clean Banks
        $banksCleaned = $this->cleanProfileAbout(Bank::class, 'Banks');
        $totalCleaned += $banksCleaned;

        // Clean Admins
        $adminsCleaned = $this->cleanProfileAbout(Admin::class, 'Admins');
        $totalCleaned += $adminsCleaned;

        $this->newLine();
        $this->info("Cleanup complete! Total profiles cleaned: {$totalCleaned}");

        return Command::SUCCESS;
    }

    /**
     * Clean the about field for a specific model type.
     *
     * @param string $modelClass
     * @param string $displayName
     * @return int
     */
    private function cleanProfileAbout(string $modelClass, string $displayName): int
    {
        // Find all profiles where about field contains only the empty paragraph or single quote
        $profiles = $modelClass::where('about', '<p></p>')
            ->orWhere('about', '<p> </p>')
            ->orWhere('about', '<p>&nbsp;</p>')
            ->orWhere('about', '"')
            ->get();

        $count = $profiles->count();

        if ($count === 0) {
            $this->line("✓ {$displayName}: No profiles to clean");
            return 0;
        }

        $bar = $this->output->createProgressBar($count);
        $bar->setFormat(" {$displayName}: [%bar%] %current%/%max% (%percent:3s%%)");

        foreach ($profiles as $profile) {
            $profile->about = null;
            $profile->save();
            $bar->advance();
        }

        $bar->finish();
        $this->newLine();

        return $count;
    }
}
