<?php

namespace App\Http\Resources\Messenger;

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

class MessageResource extends JsonResource
{
    public function toArray($request): array
    {
        $userId = Auth::id();
        
        return [
            'id' => $this->id,
            'conversation_id' => $this->conversation_id,
            'user' => new UserShortResource($this->whenLoaded('user')),
            'type' => $this->type,
            'content' => $this->when(!$this->is_deleted, $this->content),
            'attachments' => MessageAttachmentResource::collection($this->whenLoaded('attachments')),
            'reply_to' => $this->when(
                $this->reply_to_message_id && $this->relationLoaded('replyToMessage'),
                new MessageResource($this->replyToMessage)
            ),
            'is_edited' => $this->isEdited(),
            'is_deleted' => $this->is_deleted,
            'is_system' => $this->isSystemMessage(),
            'is_own' => $this->user_id === $userId,
            'client_generated_id' => $this->client_generated_id,
            'delivery_status' => $this->when(
                $this->user_id === $userId && !$this->isSystemMessage(),
                $this->getDeliveryStatus()
            ),
            'metadata' => $this->when($this->metadata, $this->metadata),
            'created_at' => $this->created_at?->toISOString(),
            'edited_at' => $this->edited_at?->toISOString(),
        ];
    }
}
