<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class FreelanceBrief extends Model
{
    use HasFactory;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'user_id',
        'hub_id',
        'title',
        'description',
        'required_skills',
        'preferred_sector',
        'duration_estimate',
        'timeline',
        'budget_min_egp',
        'budget_max_egp',
        'budget_is_visible',
        'status',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'required_skills'   => 'array',
        'budget_is_visible' => 'boolean',
        'budget_min_egp'    => 'integer',
        'budget_max_egp'    => 'integer',
    ];

    // ── Helpers ───────────────────────────────────────────────

    public function getBudgetRangeAttribute(): ?string
    {
        if (! $this->budget_is_visible) {
            return null;
        }
        if ($this->budget_min_egp && $this->budget_max_egp) {
            return 'EGP ' . number_format($this->budget_min_egp)
                 . ' – ' . number_format($this->budget_max_egp);
        }
        return null;
    }

    public function isOpen(): bool
    {
        return $this->status === 'open';
    }

    // ── Scopes ────────────────────────────────────────────────

    public function scopeOpen(Builder $query): Builder
    {
        return $query->where('status', 'open');
    }

    public function scopeForHub(Builder $query, int $hubId): Builder
    {
        return $query->where('hub_id', $hubId);
    }

    // ── Relationships ─────────────────────────────────────────

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

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

    public function matches(): HasMany
    {
        return $this->hasMany(FreelanceMatch::class);
    }
}
