<?php

namespace App\Http\Controllers;

use App\Support\CronLogSanitizer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;

class CronExecutionController extends Controller
{
    /**
     * Allowed scheduled Artisan commands callable through the cron runner.
     *
     * @var array<string>
     */
    public const ALLOWED_COMMANDS = [
        'schedule:run',
        'campaigns:sync-performance',
        'platforms:refresh-tokens',
        'queue:prune-failed',
        'queue:prune-batches',
    ];

    /**
     * Handle incoming cron execution request.
     */
    public function __invoke(Request $request, CronLogSanitizer $sanitizer): JsonResponse
    {
        $requestContext = [
            'request_id' => $request->header('X-Request-ID') ?: (string) Str::uuid(),
            'method' => $request->method(),
            'path' => '/'.$request->path(),
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'query' => $sanitizer->sanitizeInput($request->query()),
            'input' => $sanitizer->sanitizeInput($request->all()),
            'cron_token_present' => filled($request->header('X-Cron-Token') ?: $request->input('token')),
        ];
        Log::channel('cron')->info('Cron request received', $requestContext);

        // If CRON_TOKEN is set in environment, enforce strict token validation.
        // If not set, access is governed by network/VPC perimeter (matching legacy adcenter/advertisers).
        $configuredToken = config('app.cron_token');
        if (! empty($configuredToken)) {
            $providedToken = $request->header('X-Cron-Token') ?: $request->input('token');
            if (! hash_equals((string) $configuredToken, (string) $providedToken)) {
                Log::channel('cron')->warning('Cron request rejected', $requestContext + [
                    'http_status' => 401,
                    'reason' => 'invalid_token',
                ]);

                return response()->json([
                    'status' => 'error',
                    'message' => 'Unauthorized: Invalid cron token',
                ], 401);
            }
        }

        $command = (string) $request->input('command', 'schedule:run');

        if (! in_array($command, self::ALLOWED_COMMANDS, true)) {
            Log::channel('cron')->warning('Cron request rejected', $requestContext + [
                'command' => $sanitizer->sanitizeText($command),
                'http_status' => 400,
                'reason' => 'command_not_allowed',
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Command not allowed',
                'allowed_commands' => self::ALLOWED_COMMANDS,
            ], 400);
        }

        @set_time_limit(300);

        $startedAt = microtime(true);

        try {
            $exitCode = Artisan::call($command);
            $output = $sanitizer->sanitizeText(trim(Artisan::output()));
            $httpStatus = $exitCode === 0 ? 200 : 500;
            $status = $exitCode === 0 ? 'success' : 'failed';
            $context = $requestContext + [
                'command' => $sanitizer->sanitizeText($command),
                'exit_code' => $exitCode,
                'http_status' => $httpStatus,
                'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000),
                'output' => $output,
            ];

            Log::channel('cron')->log($exitCode === 0 ? 'info' : 'error', 'Cron command completed', $context);

            return response()->json([
                'status' => $status,
                'command' => $command,
                'exit_code' => $exitCode,
                'output' => $output,
            ], $httpStatus);
        } catch (Throwable $exception) {
            Log::channel('cron')->error('Cron command threw an exception', $requestContext + [
                'command' => $sanitizer->sanitizeText($command),
                'http_status' => 500,
                'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000),
                'exception' => $exception::class,
                'message' => $sanitizer->sanitizeText($exception->getMessage()),
            ]);

            throw $exception;
        }

    }
}
