<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\PlatformConnection;
use App\Services\Quality\DataQualityService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DataQualityController extends Controller
{
    public function index(Request $request, DataQualityService $quality): View
    {
        $validated = $request->validate([
            'client_id' => ['nullable', 'integer', 'exists:clients,id'],
            'platform' => ['nullable', 'in:google_ads,meta_ads,search_console,ga4'],
            'connection_id' => ['nullable', 'integer', 'exists:platform_connections,id'],
            'from' => ['nullable', 'date'],
            'to' => ['nullable', 'date', 'after_or_equal:from'],
            'save' => ['nullable', 'boolean'],
        ]);

        $from = $validated['from'] ?? now()->subDays(7)->toDateString();
        $to = $validated['to'] ?? now()->subDay()->toDateString();
        $clientId = isset($validated['client_id']) ? (int) $validated['client_id'] : null;
        $connectionId = isset($validated['connection_id']) ? (int) $validated['connection_id'] : null;
        $platform = $validated['platform'] ?? null;

        $connections = PlatformConnection::with('client')
            ->when($clientId, fn ($q) => $q->where('client_id', $clientId))
            ->when($platform, fn ($q) => $q->where('platform', $platform))
            ->orderBy('platform')
            ->orderBy('connection_name')
            ->get();

        $report = $quality->analyze($clientId, $platform, $connectionId, $from, $to, (bool) ($validated['save'] ?? false));

        return view('admin.sync.quality', [
            'page_title' => 'Veri Kalite Kontrolü',
            'page_description' => 'Snapshot sonrası veri bütünlüğü, tarih boşlukları ve rapora hazır olma kontrolü',
            'clients' => Client::orderBy('company_name')->get(),
            'connections' => $connections,
            'report' => $report,
            'filters' => [
                'client_id' => $clientId,
                'platform' => $platform,
                'connection_id' => $connectionId,
                'from' => $from,
                'to' => $to,
            ],
        ]);
    }

    public function runConnection(Request $request, PlatformConnection $connection, DataQualityService $quality): RedirectResponse
    {
        $validated = $request->validate([
            'from' => ['nullable', 'date'],
            'to' => ['nullable', 'date', 'after_or_equal:from'],
            'save' => ['nullable', 'boolean'],
        ]);

        $from = $validated['from'] ?? now()->subDays(7)->toDateString();
        $to = $validated['to'] ?? now()->subDay()->toDateString();
        $result = $quality->analyzeConnection($connection->load('client'), $from, $to, null, (bool) ($validated['save'] ?? true));

        return redirect()
            ->route('admin.sync.quality', [
                'client_id' => $connection->client_id,
                'platform' => $connection->platform,
                'connection_id' => $connection->id,
                'from' => $from,
                'to' => $to,
            ])
            ->with($result['status'] === 'danger' ? 'error' : 'success', $connection->connection_name.' kalite kontrol sonucu: '.$result['status_label'].' · Skor: '.$result['score'].'/100');
    }
}
