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

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'freelance_brief_id',
        'freelance_profile_id',
        'seeker_user_id',
        'provider_user_id',
        'status',
        'seeker_consented',
        'provider_consented',
        'connected_at',
        'seeker_message',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'seeker_consented'   => 'boolean',
        'provider_consented' => 'boolean',
        'connected_at'       => 'datetime',
    ];

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

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

    public function bothConsented(): bool
    {
        return $this->seeker_consented && $this->provider_consented;
    }

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

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

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

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

    public function brief(): BelongsTo
    {
        return $this->belongsTo(FreelanceBrief::class, 'freelance_brief_id');
    }

    public function profile(): BelongsTo
    {
        return $this->belongsTo(FreelanceProfile::class, 'freelance_profile_id');
    }

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

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

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