<?php

namespace App\Jobs;

use App\Jobs\Middleware\TrackOperationRun;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\Tenant;
use App\Models\User;
use App\Services\OperationRunService;
use App\Services\Providers\MicrosoftProviderInventoryCollector;
use App\Services\Providers\ProviderGateway;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\RunFailureSanitizer;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use RuntimeException;
use Throwable;

class ProviderInventorySyncJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public ?OperationRun $operationRun = null;

    public function __construct(
        public int $tenantId,
        public int $userId,
        public int $providerConnectionId,
        ?OperationRun $operationRun = null,
    ) {
        $this->operationRun = $operationRun;
    }

    /**
     * @return array<int, object>
     */
    public function middleware(): array
    {
        return [new TrackOperationRun];
    }

    public function handle(
        MicrosoftProviderInventoryCollector $collector,
        ProviderGateway $gateway,
        OperationRunService $runs,
    ): void {
        $tenant = Tenant::query()->find($this->tenantId);
        if (! $tenant instanceof Tenant) {
            throw new RuntimeException('Tenant not found.');
        }

        $user = User::query()->find($this->userId);
        if (! $user instanceof User) {
            throw new RuntimeException('User not found.');
        }

        $connection = ProviderConnection::query()
            ->where('tenant_id', $tenant->getKey())
            ->find($this->providerConnectionId);

        if (! $connection instanceof ProviderConnection) {
            throw new RuntimeException('ProviderConnection not found.');
        }

        try {
            $counts = $collector->collect($connection);
            $entraTenantName = $this->resolveEntraTenantName($connection, $gateway);

            if ($entraTenantName !== null) {
                $metadata = is_array($connection->metadata) ? $connection->metadata : [];
                $metadata['entra_tenant_name'] = $entraTenantName;
                $connection->update(['metadata' => $metadata]);
            }

            if ($this->operationRun instanceof OperationRun) {
                $this->updateRunTargetScope($this->operationRun, $connection, $entraTenantName);

                $runs->updateRun(
                    $this->operationRun,
                    status: OperationRunStatus::Completed->value,
                    outcome: OperationRunOutcome::Succeeded->value,
                    summaryCounts: $counts,
                );
            }
        } catch (Throwable $throwable) {
            if (! $this->operationRun instanceof OperationRun) {
                throw $throwable;
            }

            $message = RunFailureSanitizer::sanitizeMessage($throwable->getMessage());
            $reasonCode = RunFailureSanitizer::normalizeReasonCode($throwable->getMessage());

            $runs->updateRun(
                $this->operationRun,
                status: OperationRunStatus::Completed->value,
                outcome: OperationRunOutcome::Failed->value,
                failures: [[
                    'code' => 'inventory.sync.failed',
                    'reason_code' => $reasonCode,
                    'message' => $message !== '' ? $message : 'Inventory sync failed.',
                ]],
            );
        }
    }

    private function resolveEntraTenantName(ProviderConnection $connection, ProviderGateway $gateway): ?string
    {
        $metadata = is_array($connection->metadata) ? $connection->metadata : [];
        $existing = $metadata['entra_tenant_name'] ?? null;

        if (is_string($existing) && trim($existing) !== '') {
            return trim($existing);
        }

        try {
            $response = $gateway->getOrganization($connection);
        } catch (Throwable) {
            return null;
        }

        if (! $response->successful()) {
            return null;
        }

        $displayName = $response->data['displayName'] ?? null;

        return is_string($displayName) && trim($displayName) !== '' ? trim($displayName) : null;
    }

    private function updateRunTargetScope(OperationRun $run, ProviderConnection $connection, ?string $entraTenantName): void
    {
        $context = is_array($run->context) ? $run->context : [];
        $targetScope = $context['target_scope'] ?? [];
        $targetScope = is_array($targetScope) ? $targetScope : [];

        $targetScope['entra_tenant_id'] = $connection->entra_tenant_id;

        if (is_string($entraTenantName) && $entraTenantName !== '') {
            $targetScope['entra_tenant_name'] = $entraTenantName;
        }

        $context['target_scope'] = $targetScope;

        $run->update(['context' => $context]);
    }
}
