<?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\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');
    }

    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
    {
        return [
            'fields' => $repository->getFields(),
            'conditions' => $repository->getConditions($request->input('field')),
            'values' => $repository->getValues($request->input('field'), $request->input('condition')),
        ];
    }
}
