<?php

namespace App\Console\Commands;

use App\Events\UpdateShipmentStatus;
use Illuminate\Console\Command;
use App\Models\Asset;
use App\Services\Integrations\Asn\InsightUploadService;
use Illuminate\Support\Facades\Log;

class InsightUploadAll extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'insight:uploadall';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Upload all insight files till date.';


    /**
     * Create a new command instance.
     *
     * @param InsightUploadService $insightService The service responsible for handling insights upload processes.
     *
     * @return void
     */
    public function __construct(protected InsightUploadService $insightService)
    {
        parent::__construct();
    }


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $assetCount = 0;
        $sequenceNumber = 1;
        $errors = [];

        $path = storage_path('integration/insight');
        $patharray = getLatestFileNames($path);

        $arraySize = sizeof($patharray);

        for ($i = 0; $i < ($arraySize - 2); $i++) {
            $latestFile = $patharray[$i];

            if ($latestFile != ".." && $data = getItems($path . '/' . $latestFile)) {
                $this->info($latestFile . "\n");

                $this->processFile($data, $sequenceNumber, $assetCount, $errors);
            }
        }

        if (empty($errors) === false) {
            Log::error('Validation errors encountered: ' . json_encode($errors));
        }

        event(new UpdateShipmentStatus);

        $this->info($assetCount . " Assets Added");
    }


    /**
     * Processes each item in the provided data array to create or update assets.
     *
     * @param array $data           The data to process, expected to contain 'csvData' which is an array of items.
     * @param int   $sequenceNumber Current sequence number for processing.
     * @param int   $assetCount     Counter for the number of assets processed.
     * @param array $errors         An array to store validation errors encountered during processing.
     *
     * @return  void
     */
    private function processFile($data, &$sequenceNumber, &$assetCount, &$errors)
    {
        foreach ($data['csvData'] as $item) {
            $insightData = $this->insightService->createAsnData($item, $sequenceNumber);

            $validationErrors = $this->insightService->checkIfAsnDataValid($insightData, $sequenceNumber);

            if (empty($validationErrors) === false) {
                $errors[] = $validationErrors;
                continue;
            }

            $asset = Asset::firstOrCreate($insightData['assetData']);

            $this->insightService->createAssetHistory($asset);
            $this->insightService->updateTrackingNumber($item, 'TRACKING NUMBER', 'SERIAL NUMBER');

            $assetCount++;
            $sequenceNumber++;
        }
    }
}
