<?php

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

// ============================================
// AUTENTICAÇÃO
// ============================================

$company = authenticateCompany();

// ============================================
// PEGA JOB_ID
// ============================================

$jobUuid = $_GET['job_id'] ?? null;

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

$db = Database::getConnection();

// ============================================
// BUSCA STATUS DO JOB
// ============================================

$stmt = $db->prepare(
    'SELECT 
        job_uuid,
        status,
        total_items,
        processed_items,
        success_count,
        error_count,
        started_at,
        completed_at,
        created_at
     FROM batch_jobs 
     WHERE job_uuid = ? AND company_id = ?'
);
$stmt->bind_param('si', $jobUuid, $company['id']);
$stmt->execute();
$result = $stmt->get_result();

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

$job = $result->fetch_assoc();

jsonResponse([
    'job_id' => $job['job_uuid'],
    'status' => $job['status'],
    'total_items' => (int)$job['total_items'],
    'processed_items' => (int)$job['processed_items'],
    'success_count' => (int)$job['success_count'],
    'error_count' => (int)$job['error_count'],
    'started_at' => $job['started_at'],
    'completed_at' => $job['completed_at'],
    'created_at' => $job['created_at']
], 200);