<?php

namespace App\Http\Controllers;

use App\Http\Requests\CheckSlugRequest;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\App;

class SeoController extends Controller
{
    public function checkSlug(CheckSlugRequest $request)
    {
        $model = Relation::getMorphedModel($request->input('type'));
        if (!$model) {
            return response([
                'Unrecognized type'
            ], 422);
        }

        return [
            'used' => App::make($model)->newQuery()
                ->where('slug', $request->input('slug'))
                ->when($request->filled('id'), fn($query) => $query->where('id', '!=', $request->input('id')))
                ->exists()
        ];
    }
}
