<?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\BoardService;
use App\Services\PostService;
use App\Models\DTO\SearchData;
use App\Models\DTO\ResponseData;
use Exception;

class PostController extends Controller
{
    use CommonTrait;

    private UserService $userService;
    private BoardService $boardService;
    private PostService $postService;

    public function __construct(
        UserService $userService, BoardService $boardService, PostService $postService
    ) {
        $this->middleware(['front', 'auth']);

        $this->userService = $userService;
        $this->boardService = $boardService;
        $this->postService = $postService;
    }

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

        // 내가 작성한 게시글
        $posts = $this->boardService->userPosts(UID, $params);

        return view(layout('account.post'), [
            'posts' => $posts,
            'params' => $params,
            'menuID' => 'POST'
        ]);
    }

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

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

            if($posts['keys']) {

                $user = $request->user();
                foreach($posts['keys'] as $key) {
                    $post = $this->postService->postModel->findOrNew($key);

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

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

        return $response;
    }
}
