<?php

declare(strict_types=1);

namespace App\Http\Controllers\Concerns;

use App\Models\Project;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;

trait AuthorizesProjectAccess
{
    protected function authorizeProjectAccess(Project $project): void
    {
        $user = auth()->user();

        if (! $user) {
            abort(421, 'شما وارد سایت نشده اید!');
        }

        if ($user->hasRole('admin')) {
            return;
        }

        if ($this->userCanAccessProject($user, $project)) {
            return;
        }

        abort(403, 'دسترسی به این پروژه مجاز نیست.');
    }

    protected function userCanAccessProject(User $user, Project $project): bool
    {
        if ($user->id === $project->user_id || $user->id === $project->created_by) {
            return true;
        }

        if ($project->producer && $project->producer->user_id === $user->id) {
            return true;
        }

        return $project->orders()->where('user_id', $user->id)->exists();
    }

    protected function accessibleProjectsQuery(): Builder
    {
        $user = auth()->user();

        if ($user->hasRole('admin')) {
            return Project::query();
        }

        return Project::query()->where(function (Builder $query) use ($user): void {
            $query->where('user_id', $user->id)
                ->orWhere('created_by', $user->id)
                ->orWhereHas('producer', fn (Builder $producerQuery) => $producerQuery->where('user_id', $user->id))
                ->orWhereHas('orders', fn (Builder $orderQuery) => $orderQuery->where('user_id', $user->id));
        });
    }
}
