<?php

namespace App\Console\Commands;

use App\Events\IntegrationSyncHistory;
use App\Events\UpdateShipmentStatus;
use Illuminate\Console\Command;
use App\Models\Asset;
use App\Services\Integrations\Asn\ConnectionUploadService;
use Illuminate\Support\Facades\Session;
use App\Notifications\ConnectionImportNotification;
use Exception;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;

class ConnectionUpload extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'connection:upload {filename?}';


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


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


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $assetCount = 0;
        $path = storage_path('integration/connection');
        if (!is_dir($path)) {
            $this->error('Connection directory not found.');
            return false;
        }
        $latestFile = $this->argument('filename') ?: getLatestFileName($path);
        if ($latestFile == "..") {
            $this->error('Connection files not found.');
            return false;
        }
        $errors = [];

        Session::put('asnSyncErrors', '');

        if ($data = getItems($path . '/' . $latestFile)) {
            foreach ($data['csvData'] as $key => $item) {
                $connectionData = $this->uploadService->createAsnData($item, ($key + 1));

                $validationErrors = $this->uploadService->checkIfAsnDataValid($connectionData, ($key + 1));

                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++;
            }
        }

        $message = "Connection assets creation completed, on " . $latestFile . ". " . $assetCount . " assets created.";

        event(new UpdateShipmentStatus);

        if (!empty($errors)) {
            Session::put('asnSyncErrors', $errors);
            $message = "Connection assets creation completed with errors, on " . $latestFile . ". " . $assetCount . " assets created.";
        }

        $this->sendNotification($message);

        // Event to add sync history(sync_name, sync_status, notes).
        event(new IntegrationSyncHistory('asn-connection'));

        return $this->info($message);
    }


    /**
     * Send a Slack notification with the given message.
     *
     * @param string $message The message content to be sent as a notification.
     *
     * @return void
     */
    public function sendNotification($message)
    {
        try {
            Notification::route('slack', config('error-notification-mails.slack'))->notify(new ConnectionImportNotification($message));
        } catch (Exception $e) {
            Log::error("Notification sending failed: " . $e->getMessage());
        }
    }
}
