<?php

namespace App\Console\Commands;

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

class InsightUpload extends Command
{

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

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


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


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

        $path = storage_path('integration/insight');
        $latestFile = $this->argument('filename') ?: getLatestFileName($path);

        Session::put('asnSyncErrors', '');
        $errors = [];

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

                $validationErrors = $this->insightService->checkIfAsnDataValid($insightData, ($key + 1));

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

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

        event(new UpdateShipmentStatus);

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

        $this->sendNotification($message);

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

        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 InsightImportNotification($message));
        } catch (Exception $e) {
            Log::error("Notification sending failed: " . $e->getMessage());
        }
    }
}
