<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePropertyCategory;
use App\Http\Requests\UpdatePropertyCategory;
use App\Http\Resources\PropertyCategoryView;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Property;
use Mtc\MercuryDataModels\PropertyCategory;
use Mtc\MercuryDataModels\PropertyCategoryField;

class PropertyCategoryController extends Controller
{
    public function index(): Response
    {
        return response(PropertyCategory::query()->get());
    }

    public function store(StorePropertyCategory $request): PropertyCategoryView
    {
        $category = PropertyCategory::query()
            ->create([
                'name' => $request->input('name'),
            ]);

        return new PropertyCategoryView($category);
    }

    public function show(PropertyCategory $propertyCategory): PropertyCategoryView
    {
        $propertyCategory->load('fields');
        return new PropertyCategoryView($propertyCategory);
    }

    public function update(UpdatePropertyCategory $request, PropertyCategory $propertyCategory): PropertyCategoryView
    {
        $propertyCategory->update([
            'name' => $request->input('name'),
            'slug' => Str::slug($request->input('slug')),
            'active' => $request->input('active'),
        ]);

        $this->setFields($propertyCategory, $request->input('fields', []));

        $propertyCategory->refresh();
        $propertyCategory->load('fields');
        return new PropertyCategoryView($propertyCategory);
    }

    public function destroy(PropertyCategory $propertyCategory): Response
    {
        $propertyCategory->properties->each(fn(Property $property) => $property->delete());
        $propertyCategory->fields->each(fn(PropertyCategoryField $field) => $field->delete());
        $propertyCategory->delete();
        return response('ok');
    }

    private function setFields(PropertyCategory $propertyCategory, array $input): void
    {
        $propertyCategory->fields()
            ->whereNotIn('id', collect($input)->pluck('id'))
            ->get()
            ->each(fn(PropertyCategoryField $field) => $field->delete());

        collect($input)
            ->each(fn($fieldData, $index) => $propertyCategory->fields()->updateOrCreate([
                'id' => $fieldData['id']
            ], [
                'name' => $fieldData['name'],
                'type' => $fieldData['field_type'],
                'order' => $index,
                'active' => true,
                'data' => $fieldData,
            ]));
    }
}
