<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'phone' => $this->phone,
            'job_title' => $this->job_title,
            'department' => $this->department,
            'department_id' => $this->department_id,
            'department_name' => $this->when($this->relationLoaded('dept'), fn () => $this->dept?->name),
            'departments' => $this->when($this->relationLoaded('departments'), fn () => $this->departments->map(fn ($department) => [
                'id' => $department->id,
                'name' => $department->name,
                'type' => $department->type,
                'role_in_team' => $department->pivot?->role_in_team,
                'is_primary' => (bool) $department->pivot?->is_primary,
                'joined_at' => $department->pivot?->joined_at,
            ])->values()),
            'status' => $this->status,
            'skills' => $this->skills,
            'avatar' => $this->avatar,
            'avatar_url' => $this->avatar ? asset('storage/'.$this->avatar) : null,
            'role_id' => $this->role_id,
            'role' => new RoleResource($this->whenLoaded('role')),
            'roles' => RoleResource::collection($this->whenLoaded('roles')),
            'projects_count' => $this->when($this->projects_count !== null, $this->projects_count),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
