<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Jobs\RunGitDeployment;
use App\Models\GitDeployment;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GitWebhookController extends Controller
{
    public function __invoke(Request $request, GitDeployment $deployment, string $token): JsonResponse
    {
        if (! hash_equals($deployment->secret_token, $token)) {
            return response()->json(['message' => 'Invalid token'], 403);
        }

        if (! $deployment->auto_deploy) {
            return response()->json(['message' => 'Auto-deploy disabled'], 202);
        }

        RunGitDeployment::dispatch($deployment->id);

        return response()->json(['message' => 'Deployment queued']);
    }
}
