<?php

declare(strict_types=1);

namespace App\Http\Controllers\Helpers;

use App\Models\User;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;

class UserController
{
    public static function findUserIdByHash(?string $hash): ?int
    {
        if (!$hash || !is_string($hash)) {
            return null;
        }
        $user = User::where('hashkey', $hash)->first();
        return $user?->id;
    }

    //TODO Test this function 
    public static function getCurrentUserDescendants()
    {
        try {
            return Auth::user()->getAllDescendants();
        } catch (\Throwable $th) {
            return false;
        }
    }

    public static function getUserDescendantsbyHash(string $hashkey)
    {
        try {
            $user = User::where('hashkey', $hashkey)->firstOrFail();
            return $user->getAllDescendants();
        } catch (\Throwable $th) {
            return false;
        }
    }


    public static function checkifUserHashisADescendantofCurrentUser(string $hashkey)
    {
        try {
            $currentUser = Auth::user();
            if (!$currentUser)
                return false;

            return $currentUser
                ->getAllDescendants()
                ->pluck('hashkey')
                ->contains($hashkey);

        } catch (\Throwable $th) {
            return false;
        }
    }

    public static function checkifUserHashisAChildofCurrentUser(string $hashkey)
    {
        try {
            $currentUser = Auth::user();

            if (!$currentUser) {
                return false;
            }

            return User::where('parentuid', $currentUser->id)
                ->where('hashkey', $hashkey)
                ->exists();

        } catch (\Throwable $th) {
            return false;
        }
    }

}
