<?php

namespace App\Console\Commands;

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

class ConnectionUploadAll extends Command
{

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

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


    /**
     * Create a new command instance.
     *
     * @param ConnectionUploadService $uploadService The service responsible for handling connection uploads.
     *
     * @return void
     */
    public function __construct(protected ConnectionUploadService $uploadService)
    {
        parent::__construct();
    }


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

        $path = storage_path('integration/connection');
        if (!is_dir($path)) {
            $this->error('Connection directory not found');
            return false;
        }
        $patharray = getLatestFileNames($path);

        $arraySize = sizeof($patharray);

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

            if ($data = getItems($path . '/' . $latestFile)) {
                if ($latestFile == "..") {
                    $this->error('Connection files not found');
                    continue;
                }

                $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) {
            $connectionData = $this->uploadService->createAsnData($item, $sequenceNumber);

            $validationErrors = $this->uploadService->checkIfAsnDataValid($connectionData, $sequenceNumber);

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

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

            $this->uploadService->createAssetHistory($asset);
            $this->uploadService->updateTrackingNumber($item, 'Tracking Number', 'Serial Number');

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