<?php

namespace App\Models;

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

class ReceivedDocumentChunk extends Model
{
    use HasFactory;

    protected $fillable = [
        'received_document_id',
        'source_chunk_id',
        'unique_url',
        'chunk_index',
        'chunk_type',
        'hierarchy_level',
        'hierarchy_path',
        'title',
        'content',
        'markdown_content',
        'html_content',
        'token_count',
        'start_page',
        'end_page',
        'chunk_metadata',
    ];

    protected $casts = [
        'chunk_metadata' => 'array',
        'chunk_index' => 'integer',
        'hierarchy_level' => 'integer',
        'token_count' => 'integer',
        'start_page' => 'integer',
        'end_page' => 'integer',
    ];

    /**
     * Get the parent document.
     */
    public function document(): BelongsTo
    {
        return $this->belongsTo(ReceivedDocument::class, 'received_document_id');
    }

    /**
     * Scope for filtering by chunk type.
     */
    public function scopeOfType($query, string $type)
    {
        return $query->where('chunk_type', $type);
    }

    /**
     * Scope for filtering by hierarchy level.
     */
    public function scopeAtLevel($query, int $level)
    {
        return $query->where('hierarchy_level', $level);
    }
}
