<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\ConsultationRequest;
use App\Models\User;

class ConsultationRequestPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->hasAnyRole(['admin', 'producer', 'expert', 'employer', 'user']);
    }

    public function view(User $user, ConsultationRequest $consultationRequest): bool
    {
        if ($user->hasRole('admin')) {
            return true;
        }

        return $this->ownsAsProducer($user, $consultationRequest)
            || $this->ownsAsExpert($user, $consultationRequest);
    }

    public function create(User $user): bool
    {
        return $user->hasRole('admin')
            || $user->producer !== null
            || $user->hasRole('producer');
    }

    public function accept(User $user, ConsultationRequest $consultationRequest): bool
    {
        return $user->hasRole('admin') || $this->ownsAsExpert($user, $consultationRequest);
    }

    public function decline(User $user, ConsultationRequest $consultationRequest): bool
    {
        return $this->accept($user, $consultationRequest);
    }

    private function ownsAsProducer(User $user, ConsultationRequest $consultationRequest): bool
    {
        $producerId = $user->producer?->id;

        return $producerId !== null && (int) $consultationRequest->producer_id === (int) $producerId;
    }

    private function ownsAsExpert(User $user, ConsultationRequest $consultationRequest): bool
    {
        $expertId = $user->expert?->id;

        return $expertId !== null && (int) $consultationRequest->expert_id === (int) $expertId;
    }
}
