<?php

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

use Artemis\Faq\Models\Flag;
use Illuminate\Http\Request;
use Artemis\Faq\Traits\Flaggable;
use Illuminate\Http\JsonResponse;
use Illuminate\Database\Eloquent\Model;
use Artemis\Faq\Http\Resources\FlagResource;
use Artemis\Faq\Http\Requests\FlagStoreRequest;
use Artemis\Faq\Http\Requests\FlagUpdateRequest;
use Artemis\Faq\Http\Controllers\api\ApiController;
use Symfony\Component\HttpFoundation\Response as ResponseCode;

class FlagController extends ApiController
{
    public function index(): JsonResponse
    {
        return $this->success(FlagResource::collection(Flag::all()));
    }
    
    public function destroy(Flag $flag): JsonResponse
    {
        $flag->delete();
        
        return $this->success();
    }
    
    public function update(FlagUpdateRequest $request, Flag $flag): JsonResponse
    {
        $flag->update($request->validated());
        
        return $this->success();
    }
    
    public function show(Flag $flag): JsonResponse
    {
        return $this->success(new FlagResource($flag));
    }
    
    public function addFlag(FlagStoreRequest $request, string $flaggable, int $id): JsonResponse
    {
        /** @var Model|Flaggable $flaggableModel */
        $flaggableModel = resolveModelClass($flaggable, $id);
        
        $flaggableModel->flag($request->user(), $request->reason);
        
        return $this->success(status: ResponseCode::HTTP_CREATED);
    }
    
    public function getFlags(Request $request, string $flaggable, int $id): JsonResponse
    {
        /** @var Model|Flaggable $flaggableModel */
        $flaggableModel = resolveModelClass($flaggable, $id);
        
        $perPage = $this->getPerPage($request);
        $page = $this->getPage($request);
        
        $result = $flaggableModel->flags()->paginate(perPage: $perPage, page: $page);
        $data = [
                'data' => FlagResource::collection($result),
            ] + $this->paginateResult($result);
        
        return $this->success($data);
    }
}
