<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Requests\AutoImagingRequest;
use App\Http\Requests\AutoImagingStoreRequest;
use App\Http\Resources\AutoImagingResource;
use App\IntegrationRepository;
use App\Jobs\ImportImageListNotificationJob;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\ApiNotification;
use Mtc\MercuryDataModels\Vehicle;
use Carbon\Carbon;

class AutoImagingNotificationController extends Controller
{
    use DispatchesJobs;

    /**
     * List vehicles so auto-imaging can process them
     *
     * @param AutoImagingRequest $request
     * @return AutoImagingResource
     */
    public function index(AutoImagingRequest $request)
    {
        if (new IntegrationRepository()->isEnabled('auto-imaging') === false) {
            abort(403);
        }

        return new AutoImagingResource(
            Vehicle::query()
                ->with([
                    'make',
                    'model',
                    'dealership',
                    'fuelType',
                    'transmission',
                ])
                ->when(
                    Settings::get('image-sync-auto-imaging-include-equipment'),
                    fn ($query) => $query->with('equipment')
                )
                ->when(
                    Settings::get('image-sync-exclude-sold'),
                    fn ($query) => $query->where('is_sold', '!=', 1)
                )
                ->when(
                    Settings::get('image-sync-exclude-reserved'),
                    fn ($query) => $query->where('is_reserved', '!=', 1)
                )
                ->when(
                    Settings::get('image-sync-check-stock-arrival-date'),
                    fn ($query) => $query->whereNotNull('stock_arrival_date')
                        ->whereDate('stock_arrival_date', '<', Carbon::now())
                )
                ->where('is_reserved', false)
                ->get()
        );
    }

    /**
     * Import AutoImaging media
     *
     * @param AutoImagingStoreRequest $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedById
     */
    public function store(AutoImagingStoreRequest $request)
    {
        if (new IntegrationRepository()->isEnabled('auto-imaging') === false) {
            abort(403);
        }

        $notification = ApiNotification::query()
            ->create([
                'provider' => 'auto-imaging',
                'data' => $request->input(),
                'headers' => $request->header(),
                'data_model' => 'vehicle',
                'reference' => $request->input('vehicleId'),
            ]);

        if ($request->has('images')) {
            $this->dispatch(
                new ImportImageListNotificationJob(
                    $request->vehicle(),
                    $request->input('images'),
                    $notification,
                    'auto-imaging'
                )
            );
        }

        if ($request->vehicle()) {
            if ($request->has('Urls')) {
                $request->vehicle()->update(['interior_video_url' => $request->input('Urls.0')]);
            }

            if ($request->has('vimeoUrl')) {
                $request->vehicle()->update(['main_video_url' => $request->input('vimeoUrl')]);
            }

            if ($request->has('videoUrl')) {
                $request->vehicle()->update(['main_video_url' => $request->input('videoUrl')]);
            }

            $notification->update([
                'processed' => true
            ]);
        }

        return response([
            'status' => 'received'
        ]);
    }
}
