<?php

declare(strict_types=1);

namespace App\Http\Resources\Dashboard;

use App\Enums\PropertyRequestStatus;
use App\Support\DashboardStatusLabels;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @property-read string|null $last_message_preview
 * @property-read bool|int|string|null $last_message_is_system
 * @property-read string|null $last_message_at
 * @property-read int|null $responses_count
 *
 * @mixin \App\Models\PropertyRequest
 */
class MyRequestSummaryResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $status = $this->status instanceof PropertyRequestStatus
            ? $this->status
            : PropertyRequestStatus::from((string) $this->status);

        $lastAt = $this->last_message_at !== null
            ? Carbon::parse($this->last_message_at)->toIso8601String()
            : null;

        $rawPreview = $this->last_message_preview !== null ? (string) $this->last_message_preview : null;
        $isSystem = filter_var($this->last_message_is_system, FILTER_VALIDATE_BOOLEAN);
        $preview = $rawPreview !== null
            ? ($isSystem ? '[Système] '.$rawPreview : $rawPreview)
            : null;

        return [
            'id' => $this->id,
            'reference' => $this->reference,
            // Propositions (= réponses) sur la demande.
            'responses_count' => (int) ($this->responses_count ?? 0),
            'formatted_title' => $this->reference.' — '.$this->title,
            'title' => $this->title,
            'status' => $status->value,
            'status_label' => DashboardStatusLabels::propertyRequest($status),
            'last_message_preview' => $preview !== null ? Str::limit($preview, 160) : null,
            'last_message_at' => $lastAt,
            'updated_at' => $this->updated_at?->toIso8601String(),
        ];
    }
}
