<?php

namespace App\Services\Asn\Insight;

use App\Models\AsnUnwantedPart;
use App\Services\Asn\AbstractAsnMappingService;
use Exception;

/**
 * Service class for Insight assets unwanted parts
 */
class InsightUnwantedPartsService extends AbstractAsnMappingService
{
    public function getUnwantedPartsData()
    {
        return $asnUnwantedParts = AsnUnwantedPart::where('provider', 'insight')->get();
    }

    /**
     * Search through unwanted parts mappings
     * @return collection
     */
    public function getUnwantedPartsSearch()
    {
        $searchText = request('searchText');
        $insightMappings = AsnUnwantedPart::where('provider', 'insight');

        if ($searchText) {
            $insightMappings = $insightMappings->where('part_no',  'like', '%' . $searchText . '%');
        }

        return $insightMappings->get();
    }

    /**
     * Handles the unwanted parts bulk upload process
     * @return string
     */
    public function bulkUpload()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $extension = strtolower(request()->file('unwanted-parts-bulk-upload')->getClientOriginalExtension());
        $path = request()->file('unwanted-parts-bulk-upload')->storeAs('public/insight_mapping_bulk_upload', 'insight-unwanted-parts-' . date('YmdHis') . '.' . $extension);
        $path = storage_path('app/' . $path);
        $headerMap = Config('bulk-upload.asnUnwantedParts');
        $checkHeader =  $this->checkHeader($path, $headerMap);
        if ($checkHeader) {
            $errors = 'Upload file do not match the template';

            return compact('errors');
        }
        $errors =  $this->importUnwantedPartsMappingData($path, 'insight');
        if ($errors) {
            $message = 'Mapping completed with errors';

            return compact('message', 'errors');
        }
        $message = 'Bulk mapping successful.';
        return compact('message');
    }
}
