<?php

namespace Modules\Auth\Transformers;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;
use Modules\Position\Transformers\PositionResource;
use Modules\Rank\Transformers\RankResource;
use Modules\Unit\Transformers\UnitResource;

class SSOUserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'uuid' => $this->uuid,
            'name' => $this->name,
            'email' => $this->email,
            'army_number' => $this->army_number,
            'unit_id' => $this->unit_id,
            'rank_id' => $this->rank_id,
            'position_id' => $this->position_id,
            'phone_number' => $this->phone_number,
            'image_url' => $this->image_url ? Storage::disk('public')->url($this->image_url) : null,
            'status' => $this->status,
            'token' => $this->when(isset($this->token), $this->token),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'roles' => $this->whenLoaded('roles', function () {
                return $this->roles->map(function ($role) {
                    return [
                        'id' => $role->id,
                        'name' => $role->name,
                        'guard_name' => $role->guard_name,
                        'permissions' => $role->permissions ? $role->permissions->map(function ($permission) {
                            return [
                                'id' => $permission->id,
                                'name' => $permission->name,
                                'guard_name' => $permission->guard_name,
                                'route_name' => $permission->route_name ?? null,
                                'created_at' => $permission->created_at,
                                'updated_at' => $permission->updated_at,
                            ];
                        }) : [],
                        'created_at' => $role->created_at,
                        'updated_at' => $role->updated_at,
                    ];
                });
            }),
            'unit' => new UnitResource($this->whenLoaded('unit')),
            'rank' => new RankResource($this->whenLoaded('rank')),
            'position' => new PositionResource($this->whenLoaded('position')),
        ];
    }
}
