<?php

namespace App\Console\Commands;

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

class CdwUpload extends Command
{

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

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


    /**
     * Create a new command instance.
     *
     * @param CdwImportService $cdwService The CDW import service used for handling data import operations.
     *
     * @return void
     */
    public function __construct(protected CdwImportService $cdwService)
    {
        parent::__construct();
    }

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

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

                if ($validationErrors = $this->cdwService->checkIfAsnDataValid($cdwData, $key + 1)) {
                    $errors[] = $validationErrors;
                    continue;
                }

                $asset = Asset::firstOrCreate($cdwData['assetData']);
                $this->cdwService->createAssetHistory($asset);
                $this->cdwService->updateTrackingNumber($item, 'Tracking Number', 'Serial Number');
                $assetCount++;
            }
        }

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

        event(new UpdateShipmentStatus);

        if (empty($errors) === false) {
            $message = "CDW 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-cdw'));

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


    /**
     * Sends a notification based on the configured methods.
     *
     * @param string $message The message content to be sent as a notification.
     */
    public function sendNotification($message)
    {
        $slackEndpoint = config('error-notification-mails.slack');

        if ($slackEndpoint === false) {
            Log::error('Slack endpoint not configured.');
            return;
        }

        try {
            Notification::route('slack', $slackEndpoint)
                ->notify(new CDWImportNotification($message));
        } catch (Exception $e) {
            Log::error("Failed to send Slack notification: " . $e->getMessage());
        }
    }
}
