<?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 FreelanceProfile extends Model
{
    use HasFactory;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'user_id',
        'hub_id',
        'headline',
        'description',
        'services',
        'sector_expertise',
        'experience_level',
        'availability',
        'rate_min_egp',
        'rate_max_egp',
        'rate_is_visible',
        'review_count',
        'rating_average',
        'linkedin_url',
        'is_active',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'services'        => 'array',
        'sector_expertise'=> 'array',
        'rate_is_visible' => 'boolean',
        'is_active'       => 'boolean',
        'review_count'    => 'integer',
        'rating_average'  => 'float',
        'rate_min_egp'    => 'integer',
        'rate_max_egp'    => 'integer',
    ];

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

    public function getRateRangeAttribute(): ?string
    {
        if (! $this->rate_is_visible) {
            return null;
        }
        if ($this->rate_min_egp && $this->rate_max_egp) {
            return 'EGP ' . number_format($this->rate_min_egp)
                 . ' – ' . number_format($this->rate_max_egp) . ' / day';
        }
        return null;
    }

    public function isAvailable(): bool
    {
        return $this->is_active && $this->availability !== 'unavailable';
    }

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

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true)
                     ->where('availability', '!=', 'unavailable');
    }

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

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

    // Contact info is NEVER on this model
    // It lives on User and is only shared after mutual consent
    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);
    }

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