<?php

declare(strict_types=1);

namespace App\Http\Resources;

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

/**
 * Liste catalogue § 5.3 — demandes actives consultables par les professionnels.
 *
 * @property-read int|null $proposals_count
 *
 * @mixin \App\Models\PropertyRequest
 */
class PropertyRequestBrowseResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $status = $this->status instanceof PropertyRequestStatus
            ? $this->status
            : PropertyRequestStatus::from((string) $this->status);

        return [
            'id' => $this->id,
            'reference' => $this->reference,
            'title' => $this->title,
            'transaction_type' => $this->transaction_type instanceof \BackedEnum
                ? $this->transaction_type->value
                : $this->transaction_type,
            'property_type' => $this->property_type instanceof \BackedEnum
                ? $this->property_type->value
                : $this->property_type,
            'city_id' => $this->city_id,
            'city_name' => $this->relationLoaded('city') ? $this->city?->name : null,
            'zone_id' => $this->zone_id,
            'zone_name' => $this->relationLoaded('zone') ? $this->zone?->name : null,
            'budget_min' => $this->budget_min,
            'budget_max' => $this->budget_max,
            'surface_min' => $this->surface_min,
            'rooms' => $this->rooms,
            'bedrooms' => $this->bedrooms,
            'urgency_level' => $this->urgency_level instanceof \BackedEnum
                ? $this->urgency_level->value
                : $this->urgency_level,
            'status' => $status->value,
            'status_label' => DashboardStatusLabels::propertyRequest($status),
            'proposals_count' => (int) ($this->proposals_count ?? 0),
            'expires_at' => $this->expires_at?->toIso8601String(),
            'created_at' => $this->created_at?->toIso8601String(),
            'publisher' => $this->when(
                $this->relationLoaded('creator') && $this->creator !== null,
                fn (): array => [
                    'id' => $this->creator->id,
                    'name' => $this->creator->name,
                    'account_type' => $this->creator->account_type?->value ?? $this->creator->account_type,
                ],
            ),
        ];
    }
}
