<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ScrapeProfilesController extends Controller
{
    public function test(Request $request): JsonResponse
    {
        $request->validate([
            'url' => 'required|url',
            'class_name' => 'nullable|string',
            'element_id' => 'nullable|string',
        ]);

        $url = $request->input('url');
        $className = $request->input('class_name');
        $elementId = $request->input('element_id');

        try {
            $client = app(\App\Services\Ads\MajidApiClient::class);

            // Test the scraper
            $data = $client->divarScrape($url);

            if (empty($data)) {
                return response()->json([
                    'ok' => false,
                    'sample_count' => 0,
                    'message' => 'هیچ داده‌ای یافت نشد'
                ]);
            }

            $items = $data['items'] ?? $data['data'] ?? $data;
            $validItems = array_filter($items, function($item) {
                return !empty($item['title']) && !empty($item['link']);
            });

            return response()->json([
                'ok' => true,
                'sample_count' => count($validItems),
                'total_count' => count($items),
                'message' => 'تست موفقیت‌آمیز بود',
                'sample_data' => array_slice($validItems, 0, 3) // First 3 items as sample
            ]);

        } catch (\Throwable $e) {
            \Log::error('ScrapeProfilesController test failed', [
                'url' => $url,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'ok' => false,
                'sample_count' => 0,
                'message' => 'خطا در تست: ' . $e->getMessage()
            ], 500);
        }
    }
}

