<?php

namespace App\Http\Controllers\Api\Jira;

use App\Services\Api\ApiService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Asset;
use Exception;

/**
 * Controller class for the search assets from Jira plugin
 */
class TeqtivityAssetsSearchController extends controller
{
	public function index(Request $request)
	{

		try {
			if (request('search')) {
				$search 		= $request->search;
				$canBeAssigned 	= getCanBeUpdatedToStatus('assigned');
				$res    = Asset::select(['id', 'serial_no', 'asset_tag'])
					->where('serial_no', 'like', $search . '%')
					->whereHas('assetStatus', function ($query) use ($canBeAssigned) {
						$query->whereIn('slug', $canBeAssigned);
					})
					->limit(10)->get();

				$result = $res->mapWithKeys(function ($item, $key) {
					return [
						$key => [
							'id'    => $item->id,
							'type'  => 'Assets',
							'value' => $item->serial_no,
							'text' => $item->serial_no
						],
					];
				});

				return $result;
			}
		} catch (Exception $e) {
			//nothing
		}

		return null;
	}
}
