<?php

namespace App\Http\Controllers\Api\Cron;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Cron\QueueController;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Queue;

class QueueApiController extends Controller
{
    protected $queueController;

    public function __construct()
    {
        $this->queueController = new QueueController();
    }

    /**
     * Get queue status
     * @return JsonResponse
     */
    public function status(): JsonResponse
    {
        try {
            // Get queue statistics
            $stats = [
                'pending_jobs' => Queue::size(),
                'failed_jobs' => \App\Models\FailedJob::count() ?? 0,
                'processed_jobs' => \Illuminate\Support\Facades\DB::table('jobs')->count() ?? 0,
                'queue_name' => config('queue.default', 'default'),
                'connection' => config('queue.connections.' . config('queue.default') . '.driver', 'sync')
            ];

            return response()->json([
                'status' => 'success',
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch queue status',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Process queue jobs
     * @return JsonResponse
     */
    public function process(): JsonResponse
    {
        try {
            // This would typically be handled by queue workers
            // For demonstration, we'll return a success response
            return response()->json([
                'status' => 'success',
                'message' => 'Queue processing initiated',
                'timestamp' => now()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to process queue',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get failed jobs
     * @return JsonResponse
     */
    public function failedJobs(): JsonResponse
    {
        try {
            $failedJobs = [];
            
            // Check if failed jobs table exists
            if (\Illuminate\Support\Facades\Schema::hasTable('failed_jobs')) {
                $failedJobs = \Illuminate\Support\Facades\DB::table('failed_jobs')
                    ->orderBy('failed_at', 'desc')
                    ->paginate(20);
            }

            return response()->json([
                'status' => 'success',
                'data' => [
                    'failed_jobs' => $failedJobs
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch failed jobs',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Retry failed job
     * @param string $id
     * @return JsonResponse
     */
    public function retryJob($id): JsonResponse
    {
        try {
            // Retry failed job by ID
            \Illuminate\Support\Facades\Artisan::call('queue:retry', ['id' => $id]);

            return response()->json([
                'status' => 'success',
                'message' => "Job {$id} has been queued for retry",
                'timestamp' => now()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => "Failed to retry job {$id}",
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Clear failed jobs
     * @return JsonResponse
     */
    public function clearFailed(): JsonResponse
    {
        try {
            \Illuminate\Support\Facades\Artisan::call('queue:flush');

            return response()->json([
                'status' => 'success',
                'message' => 'All failed jobs have been cleared',
                'timestamp' => now()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to clear failed jobs',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
