<?php

declare(strict_types=1);

namespace App\Policies;

use App\Enums\UserRole;
use App\Models\Branch;
use App\Models\User;

class UserPolicy
{
    public function viewAny(User $user): bool
    {
        return in_array($user->role, [UserRole::SuperAdmin, UserRole::RegionAdmin], true);
    }

    public function create(User $user): bool
    {
        return in_array($user->role, [UserRole::SuperAdmin, UserRole::RegionAdmin], true);
    }

    public function update(User $user, User $target): bool
    {
        if ($user->role === UserRole::SuperAdmin) {
            return true;
        }

        if ($user->role === UserRole::RegionAdmin) {
            if ($target->region_id === $user->region_id) {
                return true;
            }

            if ($target->branch_id === null) {
                return false;
            }

            return Branch::query()->where('id', $target->branch_id)->value('region_id') === $user->region_id;
        }

        return false;
    }

    public function deactivate(User $user, User $target): bool
    {
        if ($user->id === $target->id) {
            return false;
        }

        return $this->update($user, $target);
    }

    public function activate(User $user, User $target): bool
    {
        return $this->update($user, $target);
    }

    public function updatePassword(User $user, User $target): bool
    {
        return $this->update($user, $target);
    }
}
