<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\GeneratedReport;
use App\Services\FirstReport\FirstReportWizardService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Throwable;

class FirstReportWizardController extends Controller
{
    public function index(Request $request, FirstReportWizardService $wizard): View
    {
        [$from, $to] = $wizard->normalizeRange($request->query('from'), $request->query('to'));

        $clients = Client::query()
            ->withCount(['platformConnections', 'generatedReports', 'reportSchedules'])
            ->orderBy('company_name')
            ->paginate(20)
            ->withQueryString();

        return view('admin.first-report-wizard.index', [
            'page_title' => 'İlk Rapor Sihirbazı',
            'page_description' => 'Onboarding sonrası veri önizleme, senkron, kalite kontrol, ilk rapor ve test mailini tek akışta çalıştırın.',
            'clients' => $clients,
            'from' => $from,
            'to' => $to,
        ]);
    }

    public function show(Request $request, Client $client, FirstReportWizardService $wizard): View
    {
        $payload = $wizard->dashboardPayload($client, $request->query('from'), $request->query('to'));

        return view('admin.first-report-wizard.show', [
            'page_title' => 'İlk Rapor Sihirbazı',
            'page_description' => $client->company_name . ' için ilk rapor akışı',
            'client' => $client,
            'payload' => $payload,
            'lastResult' => session('first_report_result'),
        ]);
    }

    public function preview(Request $request, Client $client, FirstReportWizardService $wizard): RedirectResponse
    {
        $data = $this->validateRunRequest($request);
        $result = $wizard->preview($client, $data['date_from'], $data['date_to'], (int) ($data['limit'] ?? 10), $data['connection_ids'] ?? []);

        return $this->redirectWithResult($client, $data, $result, 'Canlı veri önizleme tamamlandı.');
    }

    public function sync(Request $request, Client $client, FirstReportWizardService $wizard): RedirectResponse
    {
        $data = $this->validateRunRequest($request);
        $result = $wizard->sync($client, $data['date_from'], $data['date_to'], $data['connection_ids'] ?? []);

        return $this->redirectWithResult($client, $data, $result, 'Snapshot senkronizasyon tamamlandı.');
    }

    public function quality(Request $request, Client $client, FirstReportWizardService $wizard): RedirectResponse
    {
        $data = $this->validateRunRequest($request);
        $result = $wizard->quality($client, $data['date_from'], $data['date_to'], true);

        return $this->redirectWithResult($client, $data, $result, 'Veri kalite kontrolü tamamlandı.');
    }

    public function generate(Request $request, Client $client, FirstReportWizardService $wizard): RedirectResponse
    {
        $data = $this->validateReportRequest($request);
        $report = $wizard->generateReport($client, $data, auth()->id());

        if ($report->status === 'failed') {
            return $this->redirectWithResult($client, $data, ['ok' => false, 'report_id' => $report->id, 'error' => $report->error_message], 'Rapor oluşturulamadı.', 'error');
        }

        return redirect()
            ->route('admin.reports.show', $report)
            ->with('success', 'İlk rapor oluşturuldu. Detay ekranından AI yorum veya test maili çalıştırabilirsiniz.');
    }

    public function ai(Request $request, Client $client, FirstReportWizardService $wizard): RedirectResponse
    {
        $data = $request->validate([
            'report_id' => ['required', 'integer', 'exists:generated_reports,id'],
            'force_local_ai' => ['nullable', 'boolean'],
            'regenerate_files' => ['nullable', 'boolean'],
        ]);

        $report = GeneratedReport::where('client_id', $client->id)->findOrFail((int) $data['report_id']);
        $report = $wizard->generateAi($report, $request->boolean('force_local_ai'), $request->boolean('regenerate_files', true));

        if ($report->ai_status === 'failed') {
            return back()->with('error', 'AI yorumu oluşturulamadı: ' . $report->ai_error_message);
        }

        return back()->with('success', 'AI yönetici özeti üretildi.');
    }

    public function sendTest(Request $request, Client $client, FirstReportWizardService $wizard): RedirectResponse
    {
        $data = $request->validate([
            'report_id' => ['required', 'integer', 'exists:generated_reports,id'],
            'test_recipient' => ['nullable', 'string', 'max:500'],
            'include_pdf' => ['nullable', 'boolean'],
            'include_excel' => ['nullable', 'boolean'],
            'include_csv' => ['nullable', 'boolean'],
            'include_html' => ['nullable', 'boolean'],
        ]);

        $report = GeneratedReport::where('client_id', $client->id)->findOrFail((int) $data['report_id']);

        try {
            $emailLog = $wizard->sendTest($report, $data['test_recipient'] ?? null, $data);
        } catch (Throwable $exception) {
            report($exception);
            return back()->with('error', 'Test maili gönderilemedi: ' . $exception->getMessage());
        }

        if ($emailLog->status !== 'sent') {
            return back()->with('error', 'Test maili gönderilemedi: ' . $emailLog->error_message);
        }

        return back()->with('success', 'Test maili gönderildi.');
    }

    public function runAll(Request $request, Client $client, FirstReportWizardService $wizard): RedirectResponse
    {
        $data = $this->validateReportRequest($request) + $request->validate([
            'connection_ids' => ['nullable', 'array'],
            'connection_ids.*' => ['integer', 'exists:platform_connections,id'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:50'],
            'run_preview' => ['nullable', 'boolean'],
            'run_sync' => ['nullable', 'boolean'],
            'run_quality' => ['nullable', 'boolean'],
            'run_report' => ['nullable', 'boolean'],
            'run_ai' => ['nullable', 'boolean'],
            'force_local_ai' => ['nullable', 'boolean'],
            'send_test' => ['nullable', 'boolean'],
            'test_recipient' => ['nullable', 'string', 'max:500'],
            'include_pdf' => ['nullable', 'boolean'],
            'include_excel' => ['nullable', 'boolean'],
            'include_csv' => ['nullable', 'boolean'],
            'include_html' => ['nullable', 'boolean'],
        ]);

        $data['run_preview'] = $request->boolean('run_preview', true);
        $data['run_sync'] = $request->boolean('run_sync', true);
        $data['run_quality'] = $request->boolean('run_quality', true);
        $data['run_report'] = $request->boolean('run_report', true);
        $data['run_ai'] = $request->boolean('run_ai', true);

        try {
            $result = $wizard->runAll($client, $data, auth()->id());
        } catch (Throwable $exception) {
            report($exception);
            return $this->redirectWithResult($client, $data, ['ok' => false, 'error' => $exception->getMessage()], 'İlk rapor akışı tamamlanamadı.', 'error');
        }

        $message = $result['ok'] ? 'İlk rapor akışı tamamlandı.' : 'İlk rapor akışı tamamlandı ancak bazı adımlar kontrol istiyor.';

        return $this->redirectWithResult($client, $data, $result, $message, $result['ok'] ? 'success' : 'warning');
    }

    private function validateRunRequest(Request $request): array
    {
        return $request->validate([
            'date_from' => ['required', 'date'],
            'date_to' => ['required', 'date', 'after_or_equal:date_from'],
            'connection_ids' => ['nullable', 'array'],
            'connection_ids.*' => ['integer', 'exists:platform_connections,id'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:50'],
        ]);
    }

    private function validateReportRequest(Request $request): array
    {
        return $request->validate([
            'date_from' => ['required', 'date'],
            'date_to' => ['required', 'date', 'after_or_equal:date_from'],
            'report_type' => ['required', 'in:daily,weekly,monthly,custom'],
            'report_template_id' => ['nullable', 'integer', 'exists:report_templates,id'],
            'channels' => ['nullable', 'array'],
            'channels.*' => ['in:google_ads,meta_ads,search_console,ga4'],
        ]);
    }

    private function redirectWithResult(Client $client, array $data, array $result, string $message, string $level = 'success'): RedirectResponse
    {
        return redirect()
            ->route('admin.first-report.show', [
                'client' => $client->id,
                'from' => $data['date_from'] ?? $result['from'] ?? null,
                'to' => $data['date_to'] ?? $result['to'] ?? null,
            ])
            ->with($level, $message)
            ->with('first_report_result', $result);
    }
}
