<?php

namespace App\Domain\Images\Action;

use DB;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Feeds\ToFeedAction;
use App\Domain\Images\DataTransferObjects\ImageData;

class CreateImageAction implements ToFeedAction
{
    public function __invoke(ImageData $imageData)
    {
        DB::beginTransaction();

        $imageFeed = Feed::create([
            'title' => $imageData->title,
            'body' => $imageData->body,
            'price' => $imageData->price,
            'is_paid' => $imageData->is_paid,
            'user_id' => $imageData->user->id,
            'is_ads' => false,
            'type' => 'images',
        ]);

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

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

        DB::commit();

        return $imageFeed;
    }
}
