<?php 

namespace App\Services\Api\Slackbot;

use App\Services\Api\Jira\TeqtivityAssetStatus;
use App\Services\Api\ApiService;
use Illuminate\Http\Request;
use App\Models\AssetHistory;
use App\Models\AssetStatus;
use App\Models\Asset;
use Exception;
use App\User;
use Cache;
use Auth;
use Log;

/**
 * Service class for loan asset slash command
 */
class LoanAssetService extends SlackbotApiService
{
    public function __construct(protected TeqtivityAssetStatus $statusService, protected ApiService $responseService)
	{
	}

    /**
     * Get Asset and user details for assign asset
     *
     * @param Request $request
     *
     * @return Collection
     */
    public function getAssetDetails(Request $request)
    {
        //Check slack user email is existing or not
        $slackUser = $this->getUserByEmail($request->slack_user_email);
        if (isset($slackUser['error']) && $slackUser['error'] == true) {
            return $slackUser;
        }

        //Check the Loaner user is existing or not
        $loaner = $this->getUserByEmail($request->user_email);
        if (isset($loaner['error']) && $loaner['error'] == true) {
            return $loaner;
        }

        //check permission
        if (!$slackUser->can('Slackbot Admin Tools')) {
            return $this->getErrorResponse('You do not have permission to update this asset');
        }

        //Log::info('Searched serial'. $request->serial_no);
        //Check the asset exists
        $asset = Asset::select('id', 'serial_no', 'asset_tag', 'asset_status_id')->with('assetStatus:id,name,slug')
                    ->where(function($query) use ($request){
                        $query->where('asset_tag', $request->serial_no)
                              ->orWhere('serial_no', $request->serial_no);
                    })
                    ->first();

        if (!$asset) {
            return $this->getErrorResponse('Asset not found in Teqtivity');
        }

        //Check the assign Status is existing on the Teqtivity
        $loanedStatus = AssetStatus::select('id', 'name', 'slug')->where('slug', config('slackbot.asset_status.loaned'))->first();
        if (!$loanedStatus) {
            return $this->getErrorResponse('Loaned status not found in Teqtivity');
        }

        //Check the asset is valid for the status update
        $currentStatusSlug = optional($asset->assetStatus)->slug;
        if (!in_array(config('slackbot.asset_status.loaned'), config('asset-status.' . $currentStatusSlug))) {
            return $this->getErrorResponse('The asset cannot be loaned because of status restrictions.');
        }

        //Inject the loaner user and loaned status to the asset collection
        $asset->loaner = $loaner;
        $asset->loan_status = $loanedStatus;
        //Log::info('Fetched asset'. $asset);
        return $this->getSuccessReponse($asset, 'Asset');
    }

    /**
     * Update the asset status.
     *
     * @param Request $request 
     */
    public function updateAssetStatus(Request $request)
    {
        $error = $this->statusService->validate($request);
		if ($error) {
			return $this->responseService->errorResponse($error);
		}
		try {
            //From slack bot, its coming Y-m-d format. But in Teqtivity there is a setter for this field. So we want to convert to application date format before saving
            if ($request->has('loaner_return_date')) {
                $request->merge(['loaner_return_date' => parse_date_from_db_date($request->loaner_return_date)]);
            }
            
            $response = $this->statusService->update($request);

			return $this->responseService->successResponse('', $response);

		} catch (Exception $e) {
			Log::channel('single')->info('Slackbot Status Update Error : ' . $e->getMessage());
			return $this->responseService->errorResponse('Something went wrong. Try again later');
		}
    }
}