<?php

namespace App\Domain\Images\Action;

use DB;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Feeds\ToFeedAction;
use App\Domain\Feeds\Enums\StatusEnum;
use App\Domain\Images\DataTransferObjects\ImageData;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class UpdateImageAction implements ToFeedAction
{

    public $imageFeed;

    public function __construct(Feed $imageFeed)
    {
        $this->imageFeed = $imageFeed;
    }

    public function __invoke(ImageData $imageData)
    {

        $status = $this->imageFeed->status;
        if($status === StatusEnum::BANNED()){
            $status = StatusEnum::EDITABLE();
        }
        if($status === StatusEnum::APPROVED()){
            $status = StatusEnum::EDITABLE();
        }

        DB::beginTransaction();

        $this->imageFeed->fill([
            'title' => $imageData->title,
            'body' => $imageData->body,
            'price' => $imageData->price,
            'is_paid' => $imageData->is_paid,
            'status' => $status,
            'is_ads' => false,
        ])->save();

        if($imageData->is_loaded_photos){
            foreach ($imageData->photos as $photo) {
                $this->imageFeed->addMedia($photo)->toMediaCollection('common');
            }
        }

        if($imageData->is_loaded_photos_paid){
            foreach ($imageData->photos_paid as $photo) {
                $this->imageFeed->addMedia($photo)->toMediaCollection('paid');
            }
        }

        if(count($imageData->removedItems)){
            foreach ($imageData->removedItems as $removedItem) {
                if($media = Media::find($removedItem)){
                    $media->delete();
                }
            }
        }

        DB::commit();

        return $this->imageFeed->refresh();
    }
}
