<?php

namespace App\Core\Services;

use App\Models\Role;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Hash;

/**
 * User Service
 * Handles all user-related business logic
 */
class UserService
{
    /**
     * Get all users
     */
    public function getAll(): Collection
    {
        return User::with('role')->get();
    }

    /**
     * Get paginated users
     */
    public function getPaginated(int $perPage = 15): LengthAwarePaginator
    {
        return User::with('role')->paginate($perPage);
    }

    /**
     * Get user by ID
     */
    public function getById(int $id): ?User
    {
        return User::with('role')->find($id);
    }

    /**
     * Get user by email
     */
    public function getByEmail(string $email): ?User
    {
        return User::where('email', $email)->first();
    }

    /**
     * Create a new user
     */
    public function create(array $data): User
    {
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }

        return User::create($data);
    }

    /**
     * Update a user
     */
    public function update(User $user, array $data): bool
    {
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }

        return $user->update($data);
    }

    /**
     * Delete a user
     */
    public function delete(User $user): bool
    {
        return $user->delete();
    }

    /**
     * Assign role to user
     */
    public function assignRole(User $user, Role|string|int $role): bool
    {
        if (is_string($role)) {
            $role = Role::where('slug', $role)->first();
        } elseif (is_int($role)) {
            $role = Role::find($role);
        }

        if (! $role) {
            return false;
        }

        $user->role_id = $role->id;

        return $user->save();
    }

    /**
     * Check if user has role
     */
    public function hasRole(User $user, string $roleSlug): bool
    {
        return $user->hasRole($roleSlug);
    }

    /**
     * Check if user has permission
     */
    public function hasPermission(User $user, string $permissionSlug): bool
    {
        return $user->hasPermission($permissionSlug);
    }
}
