<?php

namespace App\Services\Auth;

use Illuminate\Support\Facades\DB;

class UserRoleService
{
    public function getRoleIds(int $userId): array
    {
        return DB::table('user_roles')
            ->where('user_id', $userId)
            ->whereNull('deleted_at')
            ->pluck('role_id')
            ->map(fn ($id) => (int) $id)
            ->all();
    }

    public function hasPermissionForCrud(array $roleIds, string $permissionName, string $crudAction = 'read'): bool
    {
        if (empty($roleIds)) {
            return false;
        }

        $rows = DB::table('role_permissions as rp')
            ->join('permissions as p', 'p.id', '=', 'rp.permission_id')
            ->whereIn('rp.role_id', $roleIds)
            ->where('p.name', $permissionName)
            ->select('rp.can_create', 'rp.can_read', 'rp.can_update', 'rp.can_delete', 'rp.can_manage')
            ->get();

        foreach ($rows as $row) {
            $manage = (bool) ($row->can_manage ?? false);
            if ($manage) {
                return true;
            }

            if ($crudAction === 'create' && !empty($row->can_create)) {
                return true;
            }
            if ($crudAction === 'read' && !empty($row->can_read)) {
                return true;
            }
            if ($crudAction === 'update' && !empty($row->can_update)) {
                return true;
            }
            if ($crudAction === 'delete' && !empty($row->can_delete)) {
                return true;
            }
        }

        return false;
    }
}
