<?php

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../helpers/response.php';

// ============================================
// RECEBE NOTIFICAÇÃO DE CONCLUSÃO
// ============================================

$payload = json_decode(file_get_contents('php://input'), true);

if (!isset($payload['job_id'])) {
    jsonResponse(['error' => 'Missing job_id'], 400);
}

$jobUuid = $payload['job_id'];

$db = Database::getConnection();

// ============================================
// FINALIZA O JOB
// ============================================

$stmt = $db->prepare(
    'UPDATE batch_jobs 
     SET status = "completed", completed_at = NOW() 
     WHERE job_uuid = ?'
);
$stmt->bind_param('s', $jobUuid);
$stmt->execute();

if ($stmt->affected_rows === 0) {
    jsonResponse(['error' => 'Job not found'], 404);
}

error_log("Batch job {$jobUuid} completed via webhook");

jsonResponse(['success' => true, 'message' => 'Job marked as completed'], 200);