<?php

namespace App\Console\Commands;

use App\Models\SettingsCatalogDefinition;
use App\Services\Intune\SettingsCatalogCategoryResolver;
use Illuminate\Console\Command;

class WarmSettingsCatalogCategoriesCache extends Command
{
    protected $signature = 'intune:warm-categories-cache 
                            {--force : Force re-fetch even if cached}';

    protected $description = 'Warm the Settings Catalog categories cache by fetching category names from Graph API for all cached definitions';

    public function handle(SettingsCatalogCategoryResolver $resolver): int
    {
        $this->info('Fetching unique category IDs from cached definitions...');

        // Get all unique category IDs from cached definitions
        $categoryIds = SettingsCatalogDefinition::whereNotNull('category_id')
            ->distinct()
            ->pluck('category_id')
            ->values()
            ->toArray();

        if (empty($categoryIds)) {
            $this->warn('No category IDs found in cached definitions');
            $this->info('Run intune:warm-definitions-cache first to populate definitions');

            return self::SUCCESS;
        }

        $this->info('Found '.count($categoryIds).' unique category IDs');
        $this->newLine();

        $progressBar = $this->output->createProgressBar(count($categoryIds));
        $progressBar->start();

        $success = 0;
        $failed = 0;

        foreach ($categoryIds as $categoryId) {
            try {
                $category = $resolver->resolveOne($categoryId);

                if ($category && isset($category['displayName'])) {
                    $success++;
                    $this->line("\n✓ ".substr($categoryId, 0, 8)."... → {$category['displayName']}", 'info');
                } else {
                    $failed++;
                    $this->line("\n✗ ".substr($categoryId, 0, 8).'... → Failed to resolve', 'error');
                }
            } catch (\Exception $e) {
                $failed++;
                $this->line("\n✗ ".substr($categoryId, 0, 8)."... → Error: {$e->getMessage()}", 'error');
            }

            $progressBar->advance();
        }

        $progressBar->finish();
        $this->newLine(2);

        $this->table(
            ['Status', 'Count'],
            [
                ['✓ Successfully fetched from Graph', $success],
                ['✗ Failed', $failed],
                ['Total', count($categoryIds)],
            ]
        );

        return self::SUCCESS;
    }
}
