<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Requests\ValuationCustomerRequest;
use App\Http\Requests\ValuationRequest;
use App\Http\Resources\PageResource;
use App\Http\Resources\ValuationResource;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Mtc\ContentManager\Models\Page;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\VehicleValuation\Exceptions\ValuationRequestFailed;
use Mtc\VehicleValuation\Facades\Valuation;
use Illuminate\Http\Request;
use Mtc\VehicleValuation\Models\VehicleValuation;

class ValuationController extends Controller
{
    public function show(Request $request): PageResource|Response
    {
        if (!Valuation::hasEnabledDriver()) {
            return response('Valuations not available', 404);
        }

        $page = Page::query()
            ->where('slug', $request->input('slug', 'valuation'))
            ->active()
            ->firstOrFail();

        return new PageResource($page);
    }

    public function get(ValuationRequest $request): Response|ValuationResource
    {
        $exists_on_site = Vehicle::query()
            ->where('vrm_condensed', str_replace(' ', '', $request->input('registration_number')))
            ->exists();

        if ($exists_on_site) {
            throw ValidationException::withMessages(['Valuation not possible for this vehicle']);
        }

        try {
            if (Valuation::hasMultiStep() && !$request->filled('variant_id')) {
                return new ValuationResource(Valuation::getVehicleVariants(
                    $request->input('registration_number'),
                    $request->input('mileage')
                ));
            }
            $valuation = Valuation::get(
                $request->input('registration_number'),
                $request->input('mileage'),
                $request->input('variant_id')
            );

            if (empty($valuation)) {
                throw new \Exception('Unable to retrieve valuation');
            }

            if (Settings::get('valuation-require-customer-details')) {
                // remove valuation data from valuation to be returned
                $valuation->retail_price = null;
                $valuation->below_price = null;
                $valuation->average_price = null;
                $valuation->clean_price = null;
                $valuation->adjusted_retail_price = null;
                $valuation->adjusted_below_price = null;
                $valuation->adjusted_average_price = null;
                $valuation->adjusted_clean_price = null;
            }

            return new ValuationResource($valuation);
        } catch (ValuationRequestFailed $exception) {
            return response([
                'success' => false,
                'message' => $exception->getMessage(),
            ], 422);
        } catch (\Exception $exception) {
            Log::error('Valuation: ' . $exception->getMessage());

            return response([
                'success' => false,
                'message' => $exception->getMessage(),
            ], 422);
        }
    }

    public function submitCustomerDetails(ValuationCustomerRequest $request)
    {
        try {
            $valuation = VehicleValuation::query()
                ->where('valuation_id', '=', $request->input('valuation_id'))
                ->firstOrFail();

            $response = Valuation::sendCustomerData($request, $valuation);

            if (!$response) {
                return response([
                    'message' => 'Could not submit',
                    'valuation' => null
                ], 422);
            }

            return response([
                'message' => 'ok',
                'valuation' => new ValuationResource($valuation)
            ], 200);
        } catch (\Exception $exception) {
            Log::error('Valuation: ' . $exception->getMessage());

            return response([
                'success' => false,
                'message' => $exception->getMessage(),
            ], 422);
        }
    }
}
