<?php

namespace App\Services\Api;

use App\Models\Asset;
use App\User;
use App\Models\Location;
use App\Models\AssetStatus as AssetStatusModel;
use Facades\App\Services\Asset\AssetStatusService;
use Illuminate\Support\Facades\Validator;

class AssetUpdateStatus
{
	public function validate()
	{
		$validator = Validator::make(
			request()->all(),
			[
				// 'ticket_no' => 'required',
				'serial_no' => 'required|exists:assets,serial_no',
				'status' => 'required|exists:asset_statuses,name',

			],
			$messages = [
				'ticket_no' => "Error! No ticket# in the request",
				'serial_no' => "Error! Serial # doesn't exist",
				'status' => 'Error! unknown asset type'
			]
		);

		if ($validator->fails()) {
			return $validator->errors();
		}

		$asset = Asset::getBySerial(request('serial_no'))->first();

		$statusFrom = $asset->assetStatus->slug;

		$statusTo = AssetStatusModel::getSlugFromName(request('status'))->first();

		if (!AssetStatusService::validateStatusUpdate($statusFrom, $statusTo->slug)) {
			return 'You cannot update the asset ' . request('serial_no') . 'to ' . request('status');
		}

		if ($statusTo->has_location == 1) {
			if (!request()->has('location')) {
				return "Error! No location in the request";
			}

			if (!Location::getFromName(request('location'))->first()) {
				return "Error Location not found!";
			}
		}

		if ($statusTo->has_user == 1) {
			if (!request()->has('user_email')) {
				return "Error! No user in the request";
			}

			if (!User::where('email', request('user_email'))->first()) {
				return "User not found";
			}
		}

		return false;
	}
}
