<?php

namespace App\Http\Controllers\Admin\Integrations;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\PlatformConnection;
use App\Services\Integrations\Preview\DataPreviewService;
use Illuminate\Http\Request;

class DataPreviewController extends Controller
{
    public function index(Request $request)
    {
        $connections = PlatformConnection::with('client')
            ->when($request->filled('platform'), fn ($q) => $q->where('platform', $request->string('platform')))
            ->when($request->filled('client_id'), fn ($q) => $q->where('client_id', $request->integer('client_id')))
            ->orderBy('platform')
            ->orderBy('connection_name')
            ->get();

        $selectedConnection = null;
        if ($request->filled('connection_id')) {
            $selectedConnection = PlatformConnection::with(['client', 'secureCredential'])->find($request->integer('connection_id'));
        }

        return view('admin.integrations.preview.index', [
            'page_title' => 'Canlı Veri Önizleme',
            'clients' => Client::orderBy('company_name')->get(),
            'connections' => $connections,
            'selectedConnection' => $selectedConnection,
            'lastPreview' => $selectedConnection?->meta['last_preview_result'] ?? null,
        ]);
    }

    public function run(Request $request, DataPreviewService $preview)
    {
        $validated = $request->validate([
            'connection_id' => ['required', 'exists:platform_connections,id'],
            'from' => ['required', 'date'],
            'to' => ['required', 'date', 'after_or_equal:from'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:50'],
        ]);

        $connection = PlatformConnection::with(['client', 'secureCredential'])->findOrFail($validated['connection_id']);
        $result = $preview->preview($connection, $validated['from'], $validated['to'], (int) ($validated['limit'] ?? 10));

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

    public function runConnection(Request $request, PlatformConnection $connection, DataPreviewService $preview)
    {
        $validated = $request->validate([
            'from' => ['required', 'date'],
            'to' => ['required', 'date', 'after_or_equal:from'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:50'],
        ]);

        $result = $preview->preview($connection->load(['client', 'secureCredential']), $validated['from'], $validated['to'], (int) ($validated['limit'] ?? 10));

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