<?php

declare(strict_types=1);

namespace App\Models;

use App\Enums\PropertyRequestStatus;
use App\Enums\RequestPropertyType;
use App\Enums\TransactionType;
use App\Enums\UrgencyLevel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class PropertyRequest extends Model
{
    protected $fillable = [
        'reference',
        'created_by_user_id',
        'transaction_type',
        'property_type',
        'city_id',
        'zone_id',
        'title',
        'budget_min',
        'budget_max',
        'surface_min',
        'rooms',
        'bedrooms',
        'urgency_level',
        'desired_timeline',
        'description',
        'commission_offer',
        'status',
        'expires_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => PropertyRequestStatus::class,
            'transaction_type' => TransactionType::class,
            'property_type' => RequestPropertyType::class,
            'urgency_level' => UrgencyLevel::class,
            'budget_min' => 'decimal:2',
            'budget_max' => 'decimal:2',
            'expires_at' => 'datetime',
        ];
    }

    /**
     * Demandes publiées actives et non expirées (§ 5.3).
     *
     * @param  Builder<PropertyRequest>  $query
     * @return Builder<PropertyRequest>
     */
    public function scopeActivePublished(Builder $query): Builder
    {
        return $query
            ->where('status', PropertyRequestStatus::Active)
            ->where(function (Builder $q): void {
                $q->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            });
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by_user_id');
    }

    public function city(): BelongsTo
    {
        return $this->belongsTo(City::class);
    }

    public function zone(): BelongsTo
    {
        return $this->belongsTo(Zone::class);
    }

    public function proposals(): HasMany
    {
        return $this->hasMany(PropertyProposal::class, 'request_id');
    }

    public function conversations(): HasMany
    {
        return $this->hasMany(Conversation::class, 'request_id');
    }
}
