<?php

namespace App\Services;

use App\Models\Polymorphs\Media;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

class CartTempDeletion extends CartService {

    public function __construct(){
        parent::__construct(CartInstance::MEDIAS_DELETIONS);
    }

    /**
     * @param Media $media
     * @return mixed
     */
    public function addMediaToDelete(Media $media): mixed
    {


     //  $mediable = $media->mediable;

        return $this->addItem([
                    'id' => $media->getKey(),
                    'name' => $media->name,
                    'qty' => 1,
                    'price' =>  0,
                    "options" => [
                        "model_id" => $media->model_id,
                        "model_type" => $media->model_type,
                        "collection_name" => $media->collection_name,
                        "file_name" => $media->file_name,
                    ]
                ]);

   }

    /**
     * @param Model $mediable
     * @return array
     */
    public function processToDeleteMedias(Model $mediable) : array{
       $success = false;
       $throwable = null;

       $items = $this->getMediasForDeletions($mediable);

       $medias = filled($items) ? Media::whereIn("id",Arr::pluck($items,["id"]))->get() : null;


        if ($medias){

            $medias->each(fn($media)=> $media->delete());
            $success = true;
            $this->removeItems(Arr::pluck($items,["rowId"]));
        }

        write_log("medias/deletions", [
            "getMediasForDeletions" => $this->getMediasForDeletions($mediable),
            "items" => $items,
            "medias"=> $medias?->pluck('id')
        ]);
        return [$success,$throwable];
    }

    public function getMediasForDeletions(Model $mediable){
         $id = $mediable->getKey();
         $type = $mediable->getMorphClass();

        return  $this->getRow(function ($item) use ($id,$type){
                            $options = $item->options;
                            return (
                                ($id == $options["model_id"])
                                &&
                                ($type === $options["model_type"])
                            ) ;
                        } ,
                            false
                        )
                        ?->toArray();
    }
}
