<?php

namespace App\Classes\Jobs\Commands\V2;

use App\Classes\Modules\Transactions\Processors\ETLPDFPurchaseOrderClaudeProcessor;
use App\Events\ETLPurchaseOrderTransactionCompleteEvent;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class ETLPurchaseOrderTransactionV2CommandJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** @var array */
    private $files;

    /** @var int|null */
    private $bookingId;

    /** @var string */
    private $groupId;

    /** @var int */
    private $batchIndex;

    /** @var int */
    private $totalBatches;

    /** @var bool */
    private $isLast;

    /**
     * constructor.
     *
     * @param array $files
     * @param int|null $bookingId
     * @param string $groupId
     * @param int $batchIndex
     * @param int $totalBatches
     * @param bool $isLast
     */
    public function __construct(
        array $files,
        ?int $bookingId,
        string $groupId,
        int $batchIndex,
        int $totalBatches,
        bool $isLast = false
    ) {
        $this->files = $files;
        $this->bookingId = $bookingId;

        $this->groupId = $groupId;
        $this->batchIndex = $batchIndex;
        $this->totalBatches = $totalBatches;
        $this->isLast = $isLast;
    }

    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - ETL Purchase Order Transaction.');
        $start   = new Carbon();

        Log::info(Carbon::now() . ': Processing - ETL Purchase Order Transaction.', [
            'group_id'      => $this->groupId,
            'batch_index'   => $this->batchIndex,
            'total_batches' => $this->totalBatches,
            'is_last'       => $this->isLast,
            'file_count'    => count($this->files),
        ]);


        $cacheKey = 'etl_finished_jobs_' . $this->groupId;
        $lockKey  = $cacheKey . '_lock';
        $finished = 0;

        Cache::lock($lockKey, 300)->block(180, function () use ($cacheKey, &$finished) {

            (App()->make(ETLPDFPurchaseOrderClaudeProcessor::class))->execute($this->files, $this->bookingId, $this->batchIndex !== 1);

            // Get current counter (default 0)
            $current = Cache::get($cacheKey, 0);
            $finished = (int)$current + 1;

            // Save updated counter
            Cache::put($cacheKey, $finished, 3600);
        });

        Log::info('ETL job finished for group ' . $this->groupId, [
            'batch_index'      => $this->batchIndex,
            'total_batches'    => $this->totalBatches,
            'finished_counter' => $finished,
            'timestamp'        => now(),
        ]);

        if ($finished >= $this->totalBatches) {
            Log::info('All ETL jobs finished for group ' . $this->groupId . '. Last job finished at ' . now());
            event(new ETLPurchaseOrderTransactionCompleteEvent(true, $this->bookingId));
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - ETL Purchase Order Transaction. ElapsedTime: ' . $elapsedTime . '.');
    }
}
