<?php

namespace App;

use App\Http\Requests\StoreConfiguratorRequest;
use Exception;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\CarConfiguratorModel;
use Mtc\MercuryDataModels\CustomerCarConfiguration;
use Ramsey\Uuid\Uuid;

class ConfiguratorRepository
{
    public function storeLead(
        StoreConfiguratorRequest $request,
        CarConfiguratorModel $model
    ): CustomerCarConfiguration|false {
        try {
            $configuration = new CustomerCarConfiguration();
            $configuration->fill([
                'uuid' => Uuid::uuid4(),
                'model_id' => $model->id,
                'price' => $request->input('total'),
            ]);
            $configuration->save();

            foreach ($request->input('sections') as $index => $section) {
                $configuration->sections()->create([
                    'section_id' => $section['id'],
                    'details' => $this->sectionDetails($section),
                ]);
            }
        } catch (Exception) {
            return false;
        }
        return $configuration;
    }

    private function sectionDetails(array $section): Collection
    {
        return collect($section['items'])
            ->filter(fn ($item) => $this->isSectionItemSelected($section['selected'], $item))
            ->map(fn ($item) => [
                'id' => $item['id'],
                'name' => $item['name']
            ])
            ->values();
    }

    private function isSectionItemSelected(array|int $selected, array $item): bool
    {
        if (!is_array($selected)) {
            $selected = [$selected];
        }

        return in_array($item['id'], $selected);
    }
}
