<?php

namespace App\Http\Controllers;

use App\Http\Requests\BulkUpdateSeoDefaultRequest;
use App\Http\Requests\UpdateSeoDefaultRequest;
use App\Http\Resources\SeoDefaultResource;
use App\Traits\ExtractOgImageID;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\SeoDefault;

class SeoDefaultController extends Controller
{
    use ExtractOgImageID;

    public function __construct()
    {
        $this->middleware([
            'permission:edit-seo',
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return Collection
     */
    public function index(): Collection
    {
        return SeoDefault::query()
            ->with('ogImage.media')
            ->get()
            ->map(fn ($default) => new SeoDefaultResource($default));
    }

    public function bulkUpdate(BulkUpdateSeoDefaultRequest $request): Collection
    {
        collect($request->input('defaults', []))
            ->each(function ($input) {
                $default = SeoDefault::query()->find($input['id']);
                $default->update($input);
                !empty($input['og_image'])
                    ? Media::setUsesForModel([ $this->getID($input['og_image']) ], $default, [], true)
                    : Media::setUsesForModel([], $default, [], true);
            });
        return $this->index();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateSeoDefaultRequest  $request
     * @param  \Mtc\MercuryDataModels\SeoDefault  $default
     * @return Collection
     */
    public function update(UpdateSeoDefaultRequest $request, SeoDefault $default): Collection
    {
        $default->update($request->input());
        $request->filled('og_image')
            ? Media::setUsesForModel([ $this->getID($request->input('og_image'))], $default, [], true)
            : Media::setUsesForModel([], $default, [], true);
        return $this->index();
    }
}
