<?php
/*
 * Copyright 2024 Cloud Creativity Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace DummyApp\Http\Controllers;

use CloudCreativity\LaravelJsonApi\Http\Controllers\JsonApiController;
use CloudCreativity\LaravelJsonApi\Http\Requests\FetchRelated;
use CloudCreativity\LaravelJsonApi\Http\Requests\ValidatedRequest;
use DummyApp\Comment;
use DummyApp\Jobs\SharePost;
use DummyApp\Post;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Response;

class CommentsController extends JsonApiController
{

    /**
     * @param FetchRelated $request
     * @param Comment $comment
     * @return Response
     */
    public function sharePost(FetchRelated $request, Comment $comment): Response
    {
        $post = $comment->commentable;

        abort_unless($post instanceof Post, '404');

        SharePost::dispatch($post);

        return $this->reply()->content($post);
    }

    /**
     * @param ValidatedRequest $request
     * @throws AuthenticationException
     * @throws AuthorizationException
     */
    protected function creating(ValidatedRequest $request)
    {
        $data = $request->get("data.relationships.commentable.data");

        if ($data && 'posts' === $data['type']) {
            $this->can('comment', Post::find($data['id']));
        }
    }
}
