<?php

namespace App\Console\Commands;

use App\Models\Policy;
use App\Models\SettingsCatalogDefinition;
use App\Services\Intune\PolicySnapshotService;
use Illuminate\Console\Command;

class TestSettingsCatalogCache extends Command
{
    protected $signature = 'test:settings-catalog-cache';

    protected $description = 'Test Settings Catalog definition caching';

    public function handle(PolicySnapshotService $snapshotService): int
    {
        $this->info('Finding Settings Catalog policy...');

        $policy = Policy::where('policy_type', 'settingsCatalogPolicy')
            ->whereHas('versions', function ($q) {
                $q->whereRaw("jsonb_array_length(snapshot->'settings') > 0");
            })
            ->first();

        if (! $policy) {
            $this->error('No Settings Catalog policy with settings found');

            return 1;
        }

        $this->info("Testing with policy: {$policy->name} (ID: {$policy->id})");
        $this->info('Creating new snapshot...');

        $tenant = $policy->tenant;
        if (! $tenant) {
            $this->error('Policy has no tenant');

            return 1;
        }

        $result = $snapshotService->fetch($tenant, $policy, 'test@example.com');

        if (isset($result['failure'])) {
            $this->error('Snapshot failed: '.($result['failure']['reason'] ?? 'Unknown'));

            return 1;
        }

        // Extract snapshot data from result
        $snapshotData = [
            'payload' => $result['payload'] ?? [],
            'metadata' => $result['metadata'] ?? [],
        ];

        // Create PolicyVersion to save the snapshot
        $policy->versions()->create([
            'managed_environment_id' => $policy->managed_environment_id,
            'version_number' => $policy->versions()->max('version_number') + 1,
            'policy_type' => $policy->policy_type,
            'platform' => $policy->platform,
            'created_by' => 'test@example.com',
            'captured_at' => now(),
            'snapshot' => $snapshotData,
        ]);

        $this->info('✓ Snapshot created and saved successfully!');
        $this->newLine();

        $latestSnapshot = $policy->versions()->orderByDesc('captured_at')->first();
        $metadata = $latestSnapshot->snapshot['metadata'] ?? [];

        $this->table(
            ['Key', 'Value'],
            [
                ['definitions_cached', $metadata['definitions_cached'] ?? 'NOT SET'],
                ['definition_count', $metadata['definition_count'] ?? 'NOT SET'],
                ['settings_hydration', $metadata['settings_hydration'] ?? 'NOT SET'],
                ['Cached definitions in DB', SettingsCatalogDefinition::count()],
            ]
        );

        if (isset($metadata['definitions_cached']) && $metadata['definitions_cached']) {
            $this->info('✓ Definitions successfully cached!');

            return 0;
        } else {
            $this->warn('⚠ Definitions not cached - check logs for errors');

            return 1;
        }
    }
}
