<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\SyncPlatformConnectionJob;
use App\Models\ApiRequestLog;
use App\Models\Ga4TrafficSnapshot;
use App\Models\GoogleCampaignSnapshot;
use App\Models\GoogleKeywordSnapshot;
use App\Models\GoogleSearchTermSnapshot;
use App\Models\MetaAdsetSnapshot;
use App\Models\MetaAdSnapshot;
use App\Models\MetaCampaignSnapshot;
use App\Models\PlatformConnection;
use App\Models\SearchConsolePageSnapshot;
use App\Models\SearchConsoleQuerySnapshot;
use App\Services\Sync\DateRangeResolver;
use App\Services\Sync\PlatformSyncManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SyncController extends Controller
{
    public function index(): View
    {
        $page_title = 'Veri Senkronizasyonu';
        $page_description = 'Google Ads, Meta Ads, Search Console ve GA4 snapshot veri toplama merkezi';
        $connections = PlatformConnection::with('client')->latest()->paginate(20);
        $snapshotCounts = $this->snapshotCounts();
        $recentLogs = ApiRequestLog::latest('requested_at')->limit(10)->get();

        return view('admin.sync.index', compact('page_title', 'page_description', 'connections', 'snapshotCounts', 'recentLogs'));
    }

    public function syncConnection(Request $request, PlatformConnection $connection, DateRangeResolver $rangeResolver, PlatformSyncManager $syncManager): RedirectResponse
    {
        $validated = $request->validate([
            'from' => ['nullable', 'date'],
            'to' => ['nullable', 'date'],
            'queue' => ['nullable', 'boolean'],
        ]);
        [$from, $to] = $rangeResolver->resolve($validated['from'] ?? null, $validated['to'] ?? null);

        if ($request->boolean('queue')) {
            SyncPlatformConnectionJob::dispatch($connection->id, $from, $to);
            return back()->with('success', 'Senkronizasyon queue içine eklendi.');
        }

        $result = $syncManager->syncConnection($connection, $from, $to);

        return back()->with($result->ok ? 'success' : 'error', $result->ok ? $result->message.' Satır: '.$result->totalRows() : $result->error);
    }

    public function syncAll(Request $request, DateRangeResolver $rangeResolver): RedirectResponse
    {
        $validated = $request->validate([
            'platform' => ['nullable', 'in:google_ads,meta_ads,search_console,ga4'],
            'from' => ['nullable', 'date'],
            'to' => ['nullable', 'date'],
        ]);
        [$from, $to] = $rangeResolver->resolve($validated['from'] ?? null, $validated['to'] ?? null);

        $connections = PlatformConnection::query()
            ->when($validated['platform'] ?? null, fn ($query, $platform) => $query->where('platform', $platform))
            ->whereIn('status', ['active', 'draft', 'error'])
            ->get();

        foreach ($connections as $connection) {
            SyncPlatformConnectionJob::dispatch($connection->id, $from, $to);
        }

        return back()->with('success', $connections->count().' bağlantı queue içine eklendi.');
    }

    private function snapshotCounts(): array
    {
        return [
            'Google Kampanya' => GoogleCampaignSnapshot::count(),
            'Google Kelime' => GoogleKeywordSnapshot::count(),
            'Google Arama Terimi' => GoogleSearchTermSnapshot::count(),
            'Meta Kampanya' => MetaCampaignSnapshot::count(),
            'Meta Reklam Seti' => MetaAdsetSnapshot::count(),
            'Meta Reklam' => MetaAdSnapshot::count(),
            'GSC Sorgu' => SearchConsoleQuerySnapshot::count(),
            'GSC Sayfa' => SearchConsolePageSnapshot::count(),
            'GA4 Trafik' => Ga4TrafficSnapshot::count(),
        ];
    }
}
