<?php

namespace App\Core\Services;

use App\Models\Role;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

/**
 * Role Service
 * Handles all role-related business logic
 */
class RoleService
{
    /**
     * Get all roles
     */
    public function getAll(): Collection
    {
        return Role::where('is_active', true)->get();
    }

    /**
     * Get paginated roles
     */
    public function getPaginated(int $perPage = 15): LengthAwarePaginator
    {
        return Role::paginate($perPage);
    }

    /**
     * Get role by ID
     */
    public function getById(int $id): ?Role
    {
        return Role::find($id);
    }

    /**
     * Get role by slug
     */
    public function getBySlug(string $slug): ?Role
    {
        return Role::where('slug', $slug)->first();
    }

    /**
     * Create a new role
     */
    public function create(array $data): Role
    {
        return Role::create($data);
    }

    /**
     * Update a role
     */
    public function update(Role $role, array $data): bool
    {
        return $role->update($data);
    }

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

    /**
     * Assign permissions to a role
     */
    public function assignPermissions(Role $role, array $permissionIds): void
    {
        $role->permissions()->sync($permissionIds);
    }

    /**
     * Get default roles (Admin, Staff, Customer)
     */
    public function getDefaultRoles(): array
    {
        return [
            [
                'name' => 'Administrator',
                'slug' => 'admin',
                'description' => 'Full system access',
                'is_active' => true,
            ],
            [
                'name' => 'Staff',
                'slug' => 'staff',
                'description' => 'Staff member with limited access',
                'is_active' => true,
            ],
            [
                'name' => 'Customer',
                'slug' => 'customer',
                'description' => 'Customer access',
                'is_active' => true,
            ],
        ];
    }
}
