<?php

namespace App\Services\Intune;

use App\Models\Tenant;
use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphErrorMapper;
use Throwable;

class TenantConfigService
{
    public function __construct(private readonly GraphClientInterface $graphClient) {}

    /**
     * @return array{success:bool,error_message:?string,requires_consent:bool}
     */
    public function testConnectivity(Tenant $tenant): array
    {
        $options = $this->graphOptions($tenant);

        if ($options['tenant'] === null) {
            return [
                'success' => false,
                'error_message' => 'Tenant ID is missing',
                'requires_consent' => false,
            ];
        }

        try {
            $response = $this->graphClient->getOrganization($options);
        } catch (Throwable $throwable) {
            $mapped = GraphErrorMapper::fromThrowable($throwable, ['tenant' => $options['tenant']]);

            return [
                'success' => false,
                'error_message' => $mapped->getMessage(),
                'requires_consent' => $this->requiresConsent($mapped->getMessage()),
            ];
        }

        if ($response->failed()) {
            $message = $response->errors[0]['message'] ?? $response->errors[0] ?? 'Graph connectivity failed';

            return [
                'success' => false,
                'error_message' => is_string($message) ? $message : json_encode($message),
                'requires_consent' => $this->requiresConsent((string) $message),
            ];
        }

        return ['success' => true, 'error_message' => null, 'requires_consent' => false];
    }

    /**
     * @return array{tenant:?string,client_id:?string,client_secret:?string}
     */
    public function graphOptions(Tenant $tenant): array
    {
        return $tenant->graphOptions();
    }

    private function requiresConsent(string $message): bool
    {
        return str_contains(strtolower($message), 'consent');
    }
}
