<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Admin\Concerns;

use App\Models\Paper;
use App\Models\Question;
use App\Models\QuestionBank;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

trait AuthorizesOwnedResources
{
    private function ownedBanksQuery(Request $request): Builder
    {
        $query = QuestionBank::query();

        if ($request->user()->role !== 'admin') {
            $query->where('owner_id', $request->user()->id);
        }

        return $query;
    }

    private function authorizeBankOwner(Request $request, QuestionBank $bank): void
    {
        abort_if(! $this->ownsResource($request->user(), $bank->owner_id), 403, '权限不足');
    }

    private function authorizeQuestionOwner(Request $request, Question $question): void
    {
        $question->loadMissing('bank');

        abort_if(! $this->ownsResource($request->user(), $question->bank->owner_id), 403, '权限不足');
    }

    private function authorizePaperOwner(Request $request, Paper $paper): void
    {
        abort_if(! $this->ownsResource($request->user(), $paper->owner_id), 403, '权限不足');
    }

    private function ownsResource(User $user, int $ownerId): bool
    {
        return $user->role === 'admin' || $ownerId === $user->id;
    }
}
