<?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;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;

// ══════════════════════════════════════════════════════════════════
//  InPractice — ForumPost Model
//  Location: app/Models/ForumPost.php
//
//  Updated for Share Knowledge:
//    - post_type added to fillable + casts
//    - source_url + source_label added to fillable
//    - isQuestion() + isKnowledgeShare() helpers added
//    - scopeQuestions() + scopeKnowledgeShares() scopes added
// ══════════════════════════════════════════════════════════════════

class ForumPost extends Model
{
    use HasFactory;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'user_id',
        'hub_id',
        'post_type',
        'source_url',
        'source_label',
        'title',
        'body',
        'language',
        'posted_as_nickname',
        'visibility',
        'tags',
        'status',
        'reply_count',
        'like_count',
        'view_count',
        'is_pinned',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'tags'               => 'array',
        'posted_as_nickname' => 'boolean',
        'is_pinned'          => 'boolean',
        'reply_count'        => 'integer',
        'like_count'         => 'integer',
        'view_count'         => 'integer',
    ];

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

    public function getAuthorNameAttribute(): string
    {
        if ($this->posted_as_nickname) {
            return $this->user->nickname;
        }
        return $this->user->show_real_name
            ? $this->user->name
            : $this->user->nickname;
    }

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

    public function isOwnedBy(int $userId): bool
    {
        return $this->user_id === $userId;
    }

    public function hasBestAnswer(): bool
    {
        return $this->replies()->where('is_best_answer', true)->exists();
    }

    public function incrementViews(): void
    {
        $this->increment('view_count');
    }

    public function isQuestion(): bool
    {
        return $this->post_type === 'question';
    }

    public function isKnowledgeShare(): bool
    {
        return $this->post_type === 'knowledge_share';
    }

    // Returns the safe redirect URL for the source link
    // Always goes through /go?url= — never a bare external link
    public function getSourceRedirectUrlAttribute(): ?string
    {
        if (! $this->source_url) {
            return null;
        }
        return route('member.share.external', ['url' => $this->source_url]);
    }

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

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

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

    public function scopePinned(Builder $query): Builder
    {
        return $query->where('is_pinned', true);
    }

    public function scopeVisible(Builder $query, ?array $userHubIds = null): Builder
    {
        $hubIds = $userHubIds ?? (auth()->user()?->hubs->pluck('id')->toArray() ?? []);

        return $query->where('visibility', 'all')
                    ->orWhere(function (Builder $q) use ($hubIds) {
                        $q->where('visibility', 'hub')
                        ->whereIn('hub_id', $hubIds);
                    });
    }

    public function scopeQuestions(Builder $query): Builder
    {
        return $query->where('post_type', 'question');
    }

    public function scopeKnowledgeShares(Builder $query): Builder
    {
        return $query->where('post_type', 'knowledge_share');
    }

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

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

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

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

    public function bestAnswer(): HasOne
    {
        return $this->hasOne(ForumReply::class)->where('is_best_answer', true);
    }

    public function likes(): MorphMany
    {
        return $this->morphMany(ForumLike::class, 'likeable');
    }
}