<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreImportCondition;
use App\Http\Requests\UpdateImportCondition;
use App\Http\Resources\ImportConditionResource;
use App\ImportConditionRepository;
use App\IntegrationRepository;
use App\Jobs\RunImportConditionJob;
use App\Models\ImportCondition;
use App\Models\ImportMap;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;

class ImportConditionController extends Controller
{
    public function index()
    {
        return ImportCondition::query()->with('rules')->paginate();
    }

    public function store(StoreImportCondition $request): ImportConditionResource
    {
        return new ImportConditionResource(ImportCondition::query()
            ->create([
                'provider' => $request->input('provider'),
                'import_map_id' => $request->input('import_map_id'),
            ]));
    }

    public function show(ImportCondition $importCondition): ImportConditionResource
    {
        return new ImportConditionResource($importCondition);
    }

    public function update(
        UpdateImportCondition $request,
        ImportCondition $importCondition,
        ImportConditionRepository $repository
    ): ImportConditionResource {
        $repository->update($importCondition, $request->input());
        return new ImportConditionResource($importCondition);
    }

    public function destroy(ImportCondition $importCondition): Response
    {
        $importCondition->delete();
        return response('ok');
    }

    /**
     * Apply the condition to vehicles already in the system (queued).
     */
    public function run(ImportCondition $importCondition): Response
    {
        if ($importCondition->rules()->count() === 0) {
            return response(__('integrations.condition_run_requires_rules'), Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        RunImportConditionJob::dispatch($importCondition->id);

        return response('ok');
    }

    public function getProviders(IntegrationRepository $integrations): array
    {
        return [
            'import_maps' => ImportMap::query()->select(['id', 'name'])->get(),
            'providers' => collect($integrations->getEnabledForType('stock'))
                ->map(fn ($value, $key) => [
                    'id' => $key,
                    'name' => App::make($value['class'])->name(),
                ])
                ->values(),
        ];
    }

    public function getRuleOptions(Request $request, ImportConditionRepository $repository): array
    {
        $type = $request->input('type');

        return [
            'fields' => $repository->getFields($type),
            'conditions' => $repository->getConditions($request->input('field'), $type),
            'values' => $repository->getValues($request->input('field'), $request->input('condition')),
        ];
    }
}
