<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\RssFeed;
use App\Models\Category;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class RssFeedController extends Controller
{
    /**
     * List all feeds
     */
    public function index(): JsonResponse
    {
        $feeds = RssFeed::with(['category', 'user'])->latest()->paginate(10);
        return response()->json($feeds);
    }

    /**
     * Get helper data for the create/edit form
     */
    public function getFormData(): JsonResponse
    {
        $categories = Category::whereNull('parent_id')
            ->with(['children' => function($q) {
                $q->select('id', 'name', 'parent_id');
            }])
            ->select('id', 'name')
            ->get();

        $users = User::select('id', 'name', 'email', 'avatar', 'role')
            ->whereIn('role', ['admin', 'editor', 'user']) 
            ->orderBy('name')
            ->limit(100) 
            ->get();

        return response()->json([
            'categories' => $categories,
            'users' => $users
        ]);
    }

    /**
     * Create a new feed
     */
    public function store(Request $request): JsonResponse
    {
        // 1. Handle Boolean conversion
        $request->merge([
            'is_active' => filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN),
            'fetch_full_content' => filter_var($request->fetch_full_content, FILTER_VALIDATE_BOOLEAN),
            'is_rewrite_enabled' => filter_var($request->is_rewrite_enabled, FILTER_VALIDATE_BOOLEAN),
            'show_author' => filter_var($request->show_author, FILTER_VALIDATE_BOOLEAN),
        ]);

        // 2. Validate
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'feed_url' => 'required|url',
            'category_id' => 'required|exists:categories,id',
            'assigned_user_id' => 'required|exists:users,id',
            'posts_limit_per_crawl' => 'required|integer|min:1|max:50',
            'status_on_import' => 'required|in:published,pending,draft',
            'fetch_full_content' => 'boolean',
            'is_rewrite_enabled' => 'boolean', 
            'rewrite_prompt' => 'nullable|string', 
            'show_author' => 'boolean',
            'is_active' => 'boolean',
            'keywords_include' => 'nullable|string',
            'keywords_exclude' => 'nullable|string',
            'feed_logo_url' => 'nullable|url',
            'feed_logo_file' => 'nullable|image|max:1024',
        ]);

        // 3. Handle File Upload (Logo)
        if ($request->hasFile('feed_logo_file')) {
            $path = $request->file('feed_logo_file')->store('rss_logos', 'public');
            $data['feed_logo'] = '/storage/' . $path;
        } elseif ($request->filled('feed_logo_url')) {
            $data['feed_logo'] = $request->feed_logo_url;
        }

        // 4. Map User ID & Keywords
        $data['user_id'] = $data['assigned_user_id'];
        
        if ($request->filled('keywords_include')) {
            $data['must_contain_keywords'] = array_map('trim', explode(',', $request->keywords_include));
        }
        if ($request->filled('keywords_exclude')) {
            $data['must_not_contain_keywords'] = array_map('trim', explode(',', $request->keywords_exclude));
        }

        // Cleanup unused keys
        unset($data['assigned_user_id'], $data['feed_logo_file'], $data['feed_logo_url']);

        RssFeed::create($data);

        return response()->json(['message' => 'Feed added successfully']);
    }

    /**
     * Update an existing feed
     */
    public function update(Request $request, RssFeed $rssFeed): JsonResponse
    {
        // 1. Handle Boolean conversion
        $request->merge([
            'is_active' => filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN),
            'fetch_full_content' => filter_var($request->fetch_full_content, FILTER_VALIDATE_BOOLEAN),
            'is_rewrite_enabled' => filter_var($request->is_rewrite_enabled, FILTER_VALIDATE_BOOLEAN),
            'is_auto_category_enabled' => filter_var($request->is_auto_category_enabled, FILTER_VALIDATE_BOOLEAN),
            'show_author' => filter_var($request->show_author, FILTER_VALIDATE_BOOLEAN),
        ]);

        // 2. Validate
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'feed_url' => 'required|url',
            'category_id' => 'required|exists:categories,id',
            'assigned_user_id' => 'required|exists:users,id',
            'posts_limit_per_crawl' => 'required|integer|min:1|max:50',
            'status_on_import' => 'required|in:published,pending,draft',
            'fetch_full_content' => 'boolean',
            'is_rewrite_enabled' => 'boolean', 
            'is_auto_category_enabled' => 'boolean',
            'rewrite_prompt' => 'nullable|string', 
            'show_author' => 'boolean',
            'is_active' => 'boolean',
            'keywords_include' => 'nullable|string',
            'keywords_exclude' => 'nullable|string',
            'feed_logo_url' => 'nullable|url',
            'feed_logo_file' => 'nullable|image|max:1024',
        ]);

        // 3. Handle File Upload
        if ($request->hasFile('feed_logo_file')) {
            if ($rssFeed->feed_logo && str_contains($rssFeed->feed_logo, '/storage/')) {
                $oldPath = str_replace('/storage/', '', $rssFeed->feed_logo);
                Storage::disk('public')->delete($oldPath);
            }
            $path = $request->file('feed_logo_file')->store('rss_logos', 'public');
            $data['feed_logo'] = '/storage/' . $path;
        } elseif ($request->filled('feed_logo_url')) {
            $data['feed_logo'] = $request->feed_logo_url;
        }

        // 4. Map Data
        $data['user_id'] = $data['assigned_user_id'];
        
        $data['must_contain_keywords'] = $request->filled('keywords_include') 
            ? array_map('trim', explode(',', $request->keywords_include)) : null;
            
        $data['must_not_contain_keywords'] = $request->filled('keywords_exclude') 
            ? array_map('trim', explode(',', $request->keywords_exclude)) : null;

        unset($data['assigned_user_id'], $data['feed_logo_file'], $data['feed_logo_url']);

        $rssFeed->update($data);

        return response()->json(['message' => 'Feed updated']);
    }

    public function destroy(RssFeed $rssFeed): JsonResponse
    {
        if ($rssFeed->feed_logo && str_contains($rssFeed->feed_logo, '/storage/')) {
            $oldPath = str_replace('/storage/', '', $rssFeed->feed_logo);
            Storage::disk('public')->delete($oldPath);
        }

        $rssFeed->delete();
        return response()->json(['message' => 'Feed deleted']);
    }

    /**
     * Run Manual Crawl for a Specific Feed
     * AND process it immediately.
     */
    public function crawl(RssFeed $rssFeed): JsonResponse
    {
        // Increase time limit for this request to allow processing
        set_time_limit(300);
        ini_set('memory_limit', '512M');

        try {
            // 1. Dispatch the specific feed job to the queue
            // (This creates the job entry in the database)
            Artisan::call('rss:crawl', ['id' => $rssFeed->id]);
            
            // 2. FORCE PROCESS QUEUE IMMEDIATELY (New Addition)
            // This ensures it runs even if no background worker is active
            Artisan::call('queue:work', [
                '--stop-when-empty' => true,
                '--tries' => 3
            ]);

            return response()->json([
                'message' => 'Crawl job dispatched and processed successfully.',
                'details' => Artisan::output()
            ]);

        } catch (\Exception $e) {
            Log::error("Manual Crawl Error: " . $e->getMessage());
            
            return response()->json([
                'message' => 'Crawl Failed: ' . $e->getMessage(),
                'error_type' => 'crawler_error'
            ], 500);
        }
    }
}