<?php

namespace App\Http\Resources\Roles;

use Illuminate\Http\Resources\Json\JsonResource;

class UserWithRolesResource extends JsonResource
{
    public function toArray($request): array
    {
        $row = is_array($this->resource) ? $this->resource : (array) $this->resource;
        $roles = $row['roles'] ?? [];
        if (is_string($roles)) {
            $roles = array_filter(array_map('trim', explode(',', $roles)));
        }

        return [
            'id' => (int) ($row['id'] ?? 0),
            'firstname' => (string) ($row['firstname'] ?? ''),
            'lastname' => (string) ($row['lastname'] ?? ''),
            'email' => (string) ($row['email'] ?? ''),
            'account_id' => (string) ($row['account_id'] ?? ''),
            'roles' => array_values(array_filter($roles)),
        ];
    }
}
