<?php

namespace App\Observers;

use App\Core\Hook\HookBridge;
use App\Models\NetworkStatus;

/**
 * NetworkStatusObserver
 *
 * Fires WHMCS-named network-issue lifecycle hooks via HookBridge.
 *
 * PROCP uses NetworkStatus (not NetworkIssue). Status constants:
 *   reported, investigating, in_progress, resolved, scheduled
 *
 * Hook mapping:
 *   NetworkIssueAdd    → created
 *   NetworkIssueClose  → updated, status transitions TO resolved
 *   NetworkIssueReopen → updated, status transitions OUT OF resolved
 *   NetworkIssueEdit   → updated, no close/reopen transition
 *   NetworkIssueDelete → deleted
 */
class NetworkStatusObserver
{
    public function created(NetworkStatus $issue): void
    {
        app(HookBridge::class)->fireAction(
            'NetworkIssueAdd',
            app(HookBridge::class)->buildNetworkIssueContext($issue)
        );
    }

    public function updated(NetworkStatus $issue): void
    {
        $bridge = app(HookBridge::class);
        $ctx    = $bridge->buildNetworkIssueContext($issue);

        if ($issue->wasChanged('status')) {
            $newStatus = strtolower((string) $issue->status);
            $oldStatus = strtolower((string) $issue->getOriginal('status'));

            if ($newStatus === NetworkStatus::STATUS_RESOLVED) {
                $bridge->fireAction('NetworkIssueClose', $ctx);
                return;
            }

            if ($oldStatus === NetworkStatus::STATUS_RESOLVED) {
                $bridge->fireAction('NetworkIssueReopen', $ctx);
                return;
            }
        }

        $bridge->fireAction('NetworkIssueEdit', $ctx);
    }

    public function deleted(NetworkStatus $issue): void
    {
        app(HookBridge::class)->fireAction('NetworkIssueDelete', [
            'id'       => $issue->id,
            'issue_id' => $issue->id,
        ]);
    }
}
