<?php

namespace App\Http\Resources\Messenger;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;

class ConversationResource extends JsonResource
{
    public function toArray($request): array
    {
        $userId = Auth::id();
        
        return [
            'id' => $this->id,
            'type' => $this->type,
            'title' => $this->getDisplayName($userId),
            'description' => $this->when($this->isGroup(), $this->description),
            'avatar' => getMedia($this->getDisplayAvatar($userId), 'avatar'),
            'last_message' => $this->whenLoaded('lastMessage', function () {
                return new MessageResource($this->lastMessage);
            }),
            'last_activity_at' => $this->last_activity_at?->toISOString(),
            'is_group' => $this->isGroup(),
            'is_archived' => $this->is_archived,
            'unread_count' => $this->when(isset($this->unread_count), $this->unread_count),
            'participants_count' => $this->when($this->isGroup(), $this->participants_count ?? $this->participants()->count()),
            'participants' => $this->when(
                $this->isGroup() && $this->relationLoaded('participants'),
                ConversationParticipantResource::collection($this->participants)
            ),
            'my_role' => $this->when(
                $this->relationLoaded('participants'),
                function () use ($userId) {
                    $participant = $this->participants->firstWhere('user_id', $userId);
                    return $participant?->role;
                }
            ),
            'settings' => $this->when($this->isGroup() && $this->settings, $this->settings),
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
        ];
    }
}
