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

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'user_id',
        'hub_id',
        'original_filename',
        'stored_filename',
        'file_path',
        'file_type',
        'file_size',
        'title_en',
        'title_ar',
        'description_en',
        'description_ar',
        'language',
        'document_category',
        'tags',
        'sector_id',
        'visibility',
        'status',
        'download_count',
        'rating_count',
        'rating_average',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'tags'           => 'array',
        'file_size'      => 'integer',
        'download_count' => 'integer',
        'rating_count'   => 'integer',
        'rating_average' => 'float',
    ];

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

    public function getTitleAttribute(): string
    {
        return app()->getLocale() === 'ar'
            ? ($this->title_ar ?? $this->title_en)
            : $this->title_en;
    }

    public function getDescriptionAttribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->description_ar ?? $this->description_en)
            : $this->description_en;
    }

    public function getFileSizeFormattedAttribute(): string
    {
        $bytes = $this->file_size;
        if ($bytes >= 1048576) {
            return round($bytes / 1048576, 2) . ' MB';
        }
        return round($bytes / 1024, 2) . ' KB';
    }

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

    public function incrementDownloads(): void
    {
        $this->increment('download_count');
    }

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

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

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

    public function scopeVisible(Builder $query, array $userHubIds = []): Builder
    {
        return $query->where('visibility', 'all')
                    ->orWhere(function (Builder $q) use ($userHubIds) {
                        $q->where('visibility', 'hub')
                        ->whereIn('hub_id', $userHubIds);
                    });
    }

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

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

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

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

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