<?php

namespace Modules\Post\Policies;

use Illuminate\Auth\Access\Response;
use Modules\Post\Models\Post;
use Modules\User\Models\User;

class PostPolicy
{
    public function before(User $user, string $ability): bool|null
    {
        if ($user->isAdmin()) {
            return true;
        }

        return null;
    }

    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {
        //
    }

    /**
     * Проврка возможности просмотра новости.
     * Если пользователь не состоит ни в одной из ролей ни в одном из городов, то false
     * Далее проверка, если новость привязана к городам и у пользователя нет пересечений по этим городам, то false
     */
    public function view(User $user, Post $post): bool
    {
        $availableCities = GetAvailableCities()->pluck('id')->toArray();
        if (!$availableCities) {
            return false;
        }

        if ($postCities = $post->cities->pluck('id')->toArray()) {
            if (!array_intersect($postCities, $availableCities)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Determine whether the user can create models.
     */
    public function create(User $user): bool
    {
        if ($user->isCityManager()) {
            return true;
        }
        return false;
    }

    /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, Post $post): bool
    {
        $citiesOfManager = \Modules\CityManager\Models\CityManager::where('user_id', $user->id)->pluck('city_id')->toArray();
        if ($postCities = $post->cities->pluck('id')->toArray()) {
            if (array_intersect($postCities, $citiesOfManager)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Determine whether the user can delete the model.
     */
    public function delete(User $user, Post $post): bool
    {
        $citiesOfManager = \Modules\CityManager\Models\CityManager::where('user_id', $user->id)->pluck('city_id')->toArray();
        if ($postCities = $post->cities->pluck('id')->toArray()) {
            if (array_intersect($postCities, $citiesOfManager)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Determine whether the user can restore the model.
     */
    public function restore(User $user, Post $post): bool
    {
        return false;
    }

    /**
     * Determine whether the user can permanently delete the model.
     */
    public function forceDelete(User $user, Post $post): bool
    {
        return false;
    }
}
