<?php

namespace Artemis\Faq\Http\Controllers\api\v1;

use Illuminate\Http\Request;
use Artemis\Faq\Models\Answer;
use Artemis\Faq\Models\Question;
use Illuminate\Http\JsonResponse;
use Artemis\Faq\Http\Resources\AnswerResource;
use Artemis\Faq\Http\Requests\AnswerStoreRequest;
use Artemis\Faq\Http\Requests\AnswerUpdateRequest;
use Artemis\Faq\Http\Controllers\api\ApiController;
use Symfony\Component\HttpFoundation\Response as ResponseCode;

class AnswerController extends ApiController
{
    public function index(Request $request): JsonResponse
    {
        $perPage = $this->getPerPage($request);
        $page = $this->getPage($request);
        
        $query = Answer::query();
        $query->when($request->question_id, fn($query) => $query->where('question_id', $request->question_id))
            ->when($request->user_id, fn($query) => $query->where('user_id', $request->user_id));
        
        $answers = $query->with('question')->paginate(perPage: $perPage, page: $page);
        $data = [
                'answers' => AnswerResource::collection($answers),
            ] + $this->paginateResult($answers);
        
        return $this->success($data);
    }
    
    public function store(AnswerStoreRequest $request): JsonResponse
    {
        $question = Question::findOrFail($request->question_id);
        
        $question->answers()->create([
            'user_id' => $request->user()->id,
            'body' => $request->body,
        ]);
        
        return $this->success(status: ResponseCode::HTTP_CREATED);
    }
    
    public function show(Answer $answer): JsonResponse
    {
        return $this->success(new AnswerResource($answer));
    }
    
    public function update(AnswerUpdateRequest $request, Answer $answer): JsonResponse
    {
        $answer->update($request->validated());
        
        if ($request->is_best_answer) {
            $answer->question->best_answer_id = $answer->id;
        }
        
        return $this->success();
    }
    
    public function destroy(Answer $answer): JsonResponse
    {
        $answer->delete();
        
        return $this->success();
    }
}
