<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreDealAddon;
use App\Http\Requests\UpdateDealAddon;
use App\Http\Resources\DealAddOnList;
use App\Http\Resources\DealAddOnResource;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\DealBuilder\AddOn;

class DealAddOnController extends Controller
{
    public function index(): DealAddOnList
    {
        return new DealAddOnList(AddOn::query()->latest()->paginate());
    }

    public function store(StoreDealAddon $request): DealAddOnResource
    {
        $addOn = AddOn::query()->create($request->validated());
        return new DealAddOnResource($addOn);
    }

    public function show(AddOn $dealAddOn): DealAddOnResource
    {
        return new DealAddOnResource($dealAddOn);
    }

    public function update(UpdateDealAddon $request, AddOn $dealAddOn): DealAddOnResource
    {
        $dealAddOn->update($request->validated());
        Media::setUsesForModel($request->input('media', []), $dealAddOn);
        $conditions = collect($request->input('conditions'));
        $dealAddOn->conditions()->whereNotIn('id', $conditions->pluck('id'))->delete();
        $conditions->each(fn($condition) => $dealAddOn->conditions()->updateOrCreate(
            ['id' => $condition['id']],
            $condition
        ));

        return new DealAddOnResource($dealAddOn);
    }

    public function destroy(AddOn $addOn): DealAddOnList
    {
        $addOn->conditions()->delete();
        $addOn->delete();
        return $this->index();
    }
}
