<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\Discussion;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class DiscussionResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'name' => $this->title,
            'hashtag' => $this->hashtag,
            'initial_message' => $this->initial_message,
            'status' => $this->status,
            'status_label' => Discussion::statusOptions()[(string) $this->status] ?? $this->status,
            'project_id' => $this->project_id,
            'created_by' => $this->created_by,
            'messages_count' => $this->whenCounted('messages'),
            'participants_count' => $this->whenCounted('participants'),
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
            'project' => $this->whenLoaded('project', fn () => [
                'id' => $this->project?->id,
                'code' => $this->project?->code,
                'name' => $this->project?->name,
            ]),
            'creator' => new UserResource($this->whenLoaded('createdBy')),
            'last_message' => $this->when(
                $this->relationLoaded('latestMessage') && $this->latestMessage,
                fn () => [
                    'id' => $this->latestMessage->id,
                    'body' => $this->latestMessage->body,
                    'user_id' => $this->latestMessage->user_id,
                    'created_at' => $this->latestMessage->created_at?->toISOString(),
                    'user' => $this->latestMessage->relationLoaded('user')
                        ? new UserResource($this->latestMessage->user)
                        : null,
                ]
            ),
            'messages' => DiscussionMessageResource::collection($this->whenLoaded('messages')),
            'participants' => DiscussionParticipantResource::collection($this->whenLoaded('participants')),
        ];
    }
}
