<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PlatformConnection;
use App\Services\Integrations\Sdk\ApiSdkProbeService;
use App\Services\Integrations\Sdk\ApiSdkStatusService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class ApiSdkController extends Controller
{
    public function index(ApiSdkStatusService $status): View
    {
        $page_title = 'API SDK Durumu';
        $page_description = 'Google Ads, Meta, Search Console ve GA4 resmi SDK kurulum kontrolü';
        $summary = $status->summary();
        $packages = $status->packages();
        $extensions = $status->extensions();
        $commands = $status->installCommands();
        $warnings = $status->warnings();
        $connections = PlatformConnection::with(['client', 'secureCredential'])
            ->latest()
            ->limit(20)
            ->get();

        return view('admin.system.api-sdk', compact(
            'page_title',
            'page_description',
            'summary',
            'packages',
            'extensions',
            'commands',
            'warnings',
            'connections'
        ));
    }

    public function probe(PlatformConnection $connection, ApiSdkProbeService $probe): RedirectResponse
    {
        $connection->loadMissing('secureCredential');
        $result = $probe->probe($connection);

        $meta = $connection->meta ?? [];
        $meta['last_sdk_probe_at'] = now()->toIso8601String();
        $meta['last_sdk_probe_result'] = $result->toArray();

        $connection->forceFill([
            'status' => $result->ok ? 'active' : 'error',
            'last_error' => $result->ok ? null : $result->message,
            'meta' => $meta,
        ])->save();

        return back()->with($result->ok ? 'success' : 'error', $result->message);
    }
}
