<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Feeds\Enums\StatusEnum;
use App\Http\Requests\VideoFormRequest;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redirect;
use App\Domain\Tags\Action\CreateTagAction;
use App\Domain\Feeds\Action\CreateFeedAction;
use App\Domain\Feeds\Queries\FeedQueryBuilder;
use App\Domain\Videos\Action\CreateVideoAction;
use App\Domain\Videos\Action\UpdateVideoAction;
use App\Domain\Feeds\Service\FeedMediaTransform;
use App\Domain\Videos\DataTransferObjects\VideoData;

class VideosController extends Controller
{

    public function __construct()
    {
        $this->middleware('subs.paid')->except('show');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $filter = Request::get('filter');

        $feeds = (new FeedQueryBuilder())
            ->addType('video')
            ->search(Request::only('search'))
            ->filter($filter)
            ->enableAdvertising()
            ->build();
        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

        if(request()->wantsJson()){
            return ['collections' => $feeds, 'next' => $nextCursor];
        }

        $route = route('videos.index');
        return Inertia::render('Video/Feed', [
            'nextCursor' => $nextCursor,
            'searchFilters' => Request::all('search'),
            'feeds' => $feeds,
            'local_route' => $route,
            'active_filter' => $filter ?? 'new'
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return Inertia::render('Video/Create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(VideoFormRequest $request)
    {

        $action = new CreateFeedAction(
            new CreateVideoAction(),
            new CreateTagAction(),
        );

        $videoData = VideoData::fromRequest($request);
        $action($videoData);
        $msg = 'Видео успешно загружено и находится на модерации!';
        return Redirect::route('profile.user', auth()->user()->username)->with('success', $msg);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($slug)
    {
        $feed = new FeedQueryBuilder();
        $feed = $feed->selectBy('slug', $slug)->disablePaginate()->transformGet()->first();
        if(!$feed){
            abort(404);
        }
        return Inertia::render('Video/Show', [
            'user' => $feed['user'],
            'feed' =>  $feed,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($slug)
    {
        $feed = Feed::where('slug', $slug)->firstOrFail();

        if (!$feed->user()->is(auth()->user())) {
            abort(404);
        }
        $tags = $feed->tags()->pluck('name')->toArray();

        $mediaTransform = (new FeedMediaTransform($feed))->default();
        $mediaPreview = $mediaTransform->getPreviewObject();

        $mediaTransformCommon = $mediaTransform->spot();
        $mediaTransformPaid = (new FeedMediaTransform($feed))->paid()->spot();


        return Inertia::render('Video/Edit', [
            'feed' => $feed,
            'tags' => $tags,
            'mediaPreview' => $mediaPreview,
            'mediasCount' => count($mediaTransformCommon['medias']),
            'mediasCommon' => $mediaTransformCommon['medias'],
            'mediasPaid' => $mediaTransformPaid['medias'],
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(VideoFormRequest $request, Feed $feed)
    {
        $oldStatus = $feed->status;
        if (!$feed->user()->is(auth()->user())) {
            abort(404);
        }

        $action = new CreateFeedAction(
            new UpdateVideoAction($feed),
            new CreateTagAction(),
        );

        $videoData = VideoData::fromRequest($request);
        $action($videoData);
        $newStatus = $feed->status;

        $message = 'Видео успешно обновлено!';
        if($oldStatus === StatusEnum::APPROVED() && $newStatus === StatusEnum::EDITABLE()){
            $message = 'Видео успешно обновлено и находится на модерации!';
        }

        return Redirect::back()->with('success', $message);
    }

}
