<?php

namespace App\Http\Controllers\Account;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\CommonTrait;
use App\Services\UserService;
use App\Services\CommentService;
use App\Models\DTO\SearchData;
use App\Models\DTO\ResponseData;
use Exception;

class CommentController extends Controller
{
    use CommonTrait;

    private UserService $userService;
    private CommentService $commentService;

    public function __construct(
        UserService $userService, CommentService $commentService
    ) {
        $this->middleware(['front', 'auth']);

        $this->userService = $userService;
        $this->commentService = $commentService;
    }

    /**
     * 작성 댓글
     * @method GET|POST
	 * @see /account/comment
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->path = route('account.comment');

        // 내가 작성한 게시글
        $comments = $this->commentService->userList(UID, $params);

        return view(layout('account.comment'), [
            'comments' => $comments,
            'params' => $params,
            'menuID' => 'COMMENT'
        ]);
    }

    /**
     * 댓글 삭제
     * @method DELETE
     * @see /account/comment/delete
     */
    public function delete(Request $request, ResponseData $response): ResponseData
    {
        try {

            $posts = $request->validate([
                'keys.*' => 'required|numeric|exists:tb_comment,id',
            ]);

            if($posts['keys']) {

                $user = $request->user();
                foreach($posts['keys'] as $key) {
                    $comment = $this->commentService->commentModel->findOrNew($key);

                    if(!$comment->exists) {
                        continue;
                    }

                    if(!$comment->remove($comment, $user)) {
                        throw new Exception($key . '번 댓글은 삭제할 수 없습니다.');
                    }
                }
            }
        }catch(Exception $e) {
            $response = $response::fromException($e);
        }

        return $response;
    }
}
