<?php

namespace App\Modules\CatalogOffers\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\CatalogOffers\Http\Requests\StoreCatalogOfferRequest;
use App\Modules\CatalogOffers\Http\Requests\UpdateCatalogOfferRequest;
use App\Modules\CatalogOffers\Http\Resources\CatalogOfferList;
use App\Modules\CatalogOffers\Http\Resources\CatalogOfferView;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\CatalogOffer;

class CatalogOfferController extends Controller
{
    public function index(): CatalogOfferList
    {
        return new CatalogOfferList(CatalogOffer::query()->paginate());
    }

    public function show(CatalogOffer $catalogOffer): CatalogOfferView
    {
        return new CatalogOfferView($catalogOffer);
    }

    public function store(StoreCatalogOfferRequest $request): CatalogOfferView
    {
        $catalogOffer = CatalogOffer::query()
            ->create($request->input());
        return new CatalogOfferView($catalogOffer);
    }

    public function update(UpdateCatalogOfferRequest $request, CatalogOffer $catalogOffer): CatalogOfferView
    {
        $catalogOffer->update($request->input());
        Media::setUsesForModel(
            $request->input('media', []),
            $catalogOffer,
            [
                'primary' =>  true,
                'allowed_sizes' => config('automotive.catalog_offers_sizes', [])
            ],
        );

        $rules = collect($request->input('rules', []));

        // Remove rules not in list
        $catalogOffer->rules()
            ->whereNotIn('id', $rules->pluck('id'))
            ->delete();

        // Add/Update rules
        $rules->each(fn($rule) => $catalogOffer->rules()->updateOrCreate(['id' => $rule['id']], $rule));

        return new CatalogOfferView($catalogOffer);
    }

    public function destroy(CatalogOffer $catalogOffer): CatalogOfferList
    {
        $catalogOffer->delete();
        return $this->index();
    }
}
