<?php

namespace App\Console\Commands;

use App\Models\BackupRun;
use App\Services\IncidentManagerService;
use Illuminate\Console\Command;

/**
 * Daily review of agent-reported backup verifications.
 *
 * The agent does the heavy lifting — when a backup completes, the agent
 * computes SHA256, extracts a sample file, and reports verification_status
 * via the normal /api/agent/backups endpoint. We have no outbound agent
 * URLs so this command can't probe; it just reviews what was reported.
 *
 * Two failure modes:
 *
 *   - verification_status='failed' → critical incident (silent corruption)
 *   - verification_status='pending' for >24h on a successful run →
 *     low-severity incident ("agent didn't run its own integrity check")
 */
class VerifyBackupsCommand extends Command
{
    protected $signature = 'noc:verify-backups';
    protected $description = 'Review agent-reported backup verifications, open incidents for failures or stale checks';

    public function handle(IncidentManagerService $incidents): int
    {
        $alerted = 0;

        // 1) Confirmed failures — agent already verified and found corruption
        BackupRun::where('verification_status', 'failed')
            ->where('verified_at', '>=', now()->subDays(2))
            ->with('server')
            ->get()
            ->each(function ($run) use ($incidents, &$alerted) {
                if (!$run->server) return;
                $incidents->openOrUpdate(
                    subject: $run->server,
                    title: "Backup integrity FAILED: {$run->job_name}",
                    severity: 'critical',
                    detector: "backup_integrity_failed:{$run->id}",
                    meta: [
                        'archive_path' => $run->archive_path,
                        'finished_at' => $run->finished_at?->toIso8601String(),
                        'verification_error' => $run->verification_error,
                    ],
                );
                $alerted++;
            });

        // 2) Stale pending — successful backup never followed up with verification
        BackupRun::where('status', BackupRun::STATUS_SUCCESS)
            ->where('verification_status', 'pending')
            ->where('finished_at', '<', now()->subDay())
            ->where('finished_at', '>=', now()->subDays(7))
            ->whereNotNull('archive_path')
            ->with('server')
            ->get()
            ->each(function ($run) use ($incidents, &$alerted) {
                if (!$run->server) return;
                $incidents->openOrUpdate(
                    subject: $run->server,
                    title: "Backup verification missing: {$run->job_name}",
                    severity: 'low',
                    detector: "backup_verification_missing:{$run->id}",
                    meta: [
                        'archive_path' => $run->archive_path,
                        'finished_at' => $run->finished_at?->toIso8601String(),
                        'note' => 'Agent reported success but never ran integrity check. Verify the agent post-backup script is configured.',
                    ],
                );
                $alerted++;
            });

        $this->info("Backup verification review complete. Incidents: {$alerted}");
        return self::SUCCESS;
    }
}
