<?php

namespace App\Http\Controllers\Admin\Integrations;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\PlatformConnection;
use App\Services\Integrations\Discovery\AccountDiscoveryResult;
use App\Services\Integrations\Discovery\AccountDiscoveryService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AccountDiscoveryController extends Controller
{
    public function __construct(private readonly AccountDiscoveryService $discovery) {}

    public function index(Request $request): View
    {
        $page_title = 'Hesap / Mülk Keşfi';
        $page_description = 'OAuth/token bağlantısından erişilebilir Google Ads, Meta Ads, Search Console ve GA4 hesaplarını listele ve bağlantıya aktar.';

        $platform = $request->string('platform')->toString();
        $clientId = $request->integer('client_id') ?: null;
        $selectedConnectionId = $request->integer('connection_id') ?: null;

        $connections = PlatformConnection::with(['client', 'secureCredential'])
            ->when($platform, fn ($query) => $query->where('platform', $platform))
            ->when($clientId, fn ($query) => $query->where('client_id', $clientId))
            ->orderBy('platform')
            ->orderByDesc('updated_at')
            ->get();

        $selectedConnection = $selectedConnectionId
            ? $connections->firstWhere('id', $selectedConnectionId) ?? PlatformConnection::with(['client', 'secureCredential'])->find($selectedConnectionId)
            : $connections->first();

        $clients = Client::orderBy('company_name')->get();
        $result = session('discovery_result');

        if ($result instanceof AccountDiscoveryResult) {
            $result = $result->toArray();
        }

        return view('admin.integrations.discovery.index', compact(
            'page_title',
            'page_description',
            'connections',
            'selectedConnection',
            'clients',
            'platform',
            'clientId',
            'result'
        ));
    }

    public function discover(Request $request, PlatformConnection $connection): RedirectResponse
    {
        $data = $request->validate([
            'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
        ]);

        $result = $this->discovery->discover($connection->load(['client', 'secureCredential']), (int) ($data['limit'] ?? 50));

        $connection->update([
            'last_error' => $result->ok ? null : $result->message,
            'meta' => array_merge($connection->meta ?? [], [
                'last_discovery' => [
                    'ok' => $result->ok,
                    'message' => $result->message,
                    'count' => count($result->accounts),
                    'checked_at' => now()->toDateTimeString(),
                    'status_code' => $result->statusCode,
                ],
            ]),
        ]);

        return redirect()
            ->route('admin.integrations.discovery.index', [
                'platform' => $connection->platform,
                'client_id' => $connection->client_id,
                'connection_id' => $connection->id,
            ])
            ->with($result->ok ? 'success' : 'error', $result->message)
            ->with('discovery_result', $result->toArray());
    }

    public function attach(Request $request, PlatformConnection $connection): RedirectResponse
    {
        $data = $request->validate([
            'account_id' => ['required', 'string', 'max:255'],
            'account_name' => ['nullable', 'string', 'max:255'],
            'currency_code' => ['nullable', 'string', 'max:10'],
            'timezone' => ['nullable', 'string', 'max:120'],
            'status' => ['nullable', 'string', 'max:30'],
            'resource_name' => ['nullable', 'string', 'max:255'],
            'meta' => ['nullable', 'string'],
        ]);

        $incomingMeta = [];
        if (filled($data['meta'] ?? null)) {
            $decoded = json_decode((string) $data['meta'], true);
            $incomingMeta = is_array($decoded) ? $decoded : [];
        }

        $connection->update([
            'account_id' => $data['account_id'],
            'account_name' => $data['account_name'] ?: $data['account_id'],
            'currency_code' => filled($data['currency_code'] ?? null) ? strtoupper((string) $data['currency_code']) : $connection->currency_code,
            'timezone' => $data['timezone'] ?? $connection->timezone,
            'status' => ($data['status'] ?? 'active') === 'active' ? 'active' : $connection->status,
            'last_error' => null,
            'meta' => array_merge($connection->meta ?? [], [
                'selected_account' => [
                    'account_id' => $data['account_id'],
                    'account_name' => $data['account_name'] ?? null,
                    'resource_name' => $data['resource_name'] ?? null,
                    'currency_code' => $data['currency_code'] ?? null,
                    'timezone' => $data['timezone'] ?? null,
                    'meta' => $incomingMeta,
                    'selected_at' => now()->toDateTimeString(),
                ],
            ]),
        ]);

        return redirect()
            ->route('admin.accounts.'.str_replace('_', '-', $connection->platform).'.show', $connection)
            ->with('success', 'Seçilen hesap/mülk bağlantıya aktarıldı. Şimdi bağlantı testi ve snapshot çalıştırabilirsin.');
    }
}
