<?php

namespace App\Models;

use App\Enums\StatutBesoin;
use App\Enums\TypeService;
use App\Traits\HasStatusLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class Besoin extends Model
{
    use HasFactory, SoftDeletes, HasStatusLog;

    protected $fillable = [
        'reference', 'client_id', 'type_service', 'frequence',
        'taches_details', 'age_souhaite_min', 'age_souhaite_max',
        'salaire_propose', 'date_debut_souhaitee', 'duree_estimee',
        'quartier_id', 'ville_id', 'adresse_complete',
        'telephone_contact', 'statut', 'commentaire_admin',
    ];

    protected $hidden = ['commentaire_admin'];

    protected $casts = [
        'type_service' => TypeService::class,
        'statut' => StatutBesoin::class,
        'age_souhaite_min' => 'integer',
        'age_souhaite_max' => 'integer',
        'salaire_propose' => 'decimal:2',
        'date_debut_souhaitee' => 'date',
    ];

    // Relations
    public function client(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function ville(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Ville::class);
    }

    public function quartier(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Quartier::class);
    }

    public function mission(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(Mission::class);
    }

    // Methods
    public function peutEtreAnnuleParClient(): bool
    {
        $statut = $this->statut instanceof StatutBesoin ? $this->statut->value : $this->statut;
        return in_array($statut, [
            StatutBesoin::RECU->value,
            StatutBesoin::EN_ETUDE->value,
            StatutBesoin::PROPOSITION_FAITE->value,
        ]);
    }

    // Scopes
    public function scopeDuClient(\Illuminate\Database\Eloquent\Builder $query, int $clientId): \Illuminate\Database\Eloquent\Builder
    {
        return $query->where('client_id', $clientId);
    }

    public function scopeAvecStatut(\Illuminate\Database\Eloquent\Builder $query, string $statut): \Illuminate\Database\Eloquent\Builder
    {
        return $query->where('statut', $statut);
    }
}
