<?php

declare(strict_types=1);

namespace App\Http\Resources\Dashboard;

use App\Enums\ConversationStatus;
use App\Enums\RequestPropertyType;
use App\Support\DashboardStatusLabels;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Str;

/**
 * @property-read int $unread_count
 *
 * @mixin \App\Models\Conversation
 */
class InboxConversationSummaryResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $user = $request->user();
        $other = $user !== null && (int) $this->requester_user_id === (int) $user->id
            ? $this->proposer
            : $this->requester;

        $last = $this->latestMessage;
        $preview = $last !== null
            ? ($last->is_system ? '[Système] '.$last->message : $last->message)
            : null;

        $status = $this->status instanceof ConversationStatus
            ? $this->status
            : ConversationStatus::from((string) $this->status);

        $propertyType = $this->relationLoaded('request') ? $this->request?->property_type : null;
        $propertyTypeValue = $propertyType instanceof RequestPropertyType
            ? $propertyType->value
            : ($propertyType !== null ? (string) $propertyType : null);

        return [
            'id' => $this->id,
            'formatted_title' => $this->title,
            'property_type' => $propertyTypeValue,
            'other_party_name' => $other?->name,
            'last_message_preview' => $preview !== null ? Str::limit($preview, 160) : null,
            'last_message_at' => $last?->created_at?->toIso8601String(),
            'status' => $status->value,
            'status_label' => DashboardStatusLabels::conversation($status),
            'unread_count' => (int) ($this->unread_count ?? 0),
            'updated_at' => $this->updated_at?->toIso8601String(),
        ];
    }
}
