<?php

namespace App\Http\Controllers\Api\Platform;

use App\Http\Controllers\Controller;
use App\Models\ContentRestriction;
use App\RequestRules\Api\ContentRestrictionRequestRules;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ContentRestrictionController extends Controller
{
    /**
     * @param Request $request
     * @return Application|ResponseFactory|Response
     */
    public function add(Request $request): Response|Application|ResponseFactory
    {
        $request->validate(ContentRestrictionRequestRules::add());
        $data = $request->all();

        try {
            ContentRestriction::addRestriction($data);
            $result = ContentRestriction::getRestrictions();

            return api_response(100, "Okay", $result);
        } catch (Exception $exception) {
            log_debug(exception: $exception, prefix: 'ContentRestrictionController::add');
        }

        return api_response(101, __('errors.unknown_error'));
    }

    /**
     * Get content restrictions
     *
     * @param Request $request
     * @return Application|ResponseFactory|Response
     */
    public function getRestrictions(Request $request): Response|Application|ResponseFactory
    {
        try {
            $result = array(
                'restrictions' => ContentRestriction::getRestrictions(),
                'categories' => ContentRestriction::computeCategoryTreeForRestrictionCreation(),
            );

            return api_response(100, "Okay", $result);
        } catch (Exception $exception) {
            log_debug($exception, "ContentRestrictionController::getRestrictions");
        }

        return api_response(120, __("errors.unknown_error"));
    }

    /**
     * Delete content restriction
     *
     * @param Request $request
     * @return Application|ResponseFactory|Response
     */
    public function delete(Request $request): Response|Application|ResponseFactory
    {
        $request->validate(ContentRestrictionRequestRules::delete());

        try {
            /** @var ContentRestriction $result */
            $result = ContentRestriction::findById(
                $request->{"content_restriction_id"}
            );

            $result->deleteRestriction();

            return api_response(100, 'Ok');
        } catch (Exception $exception) {
            log_debug(exception: $exception, prefix: 'ContentRestrictionController::delete');
        }

        return api_response(101, __('errors.unknown_error'));
    }
}
