<?php

namespace App\Models;

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

class ReceivedDocument extends Model
{
    use HasFactory;

    protected $fillable = [
        'source_document_id',
        'original_filename',
        'title',
        'file_extension',
        'mime_type',
        'markdown_content',
        'html_content',
        'content_type',
        'file_size',
        'chunk_count',
        'total_pages',
        'processed_at',
        'processing_duration_seconds',
        'jurisdictions',
        'doc_categories',
        'law_subjects',
        'pathways',
        'status',
        'notes',
    ];

    protected $casts = [
        'jurisdictions' => 'array',
        'doc_categories' => 'array',
        'law_subjects' => 'array',
        'pathways' => 'array',
        'processed_at' => 'datetime',
        'file_size' => 'integer',
        'chunk_count' => 'integer',
        'total_pages' => 'integer',
        'processing_duration_seconds' => 'float',
    ];

    /**
     * Get the chunks for this document.
     */
    public function chunks(): HasMany
    {
        return $this->hasMany(ReceivedDocumentChunk::class)->orderBy('chunk_index');
    }

    /**
     * Scope for filtering by status.
     */
    public function scopeStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    /**
     * Scope for received documents.
     */
    public function scopeReceived($query)
    {
        return $query->where('status', 'received');
    }

    /**
     * Scope for updated documents.
     */
    public function scopeUpdated($query)
    {
        return $query->where('status', 'updated');
    }

    /**
     * Get jurisdiction names as a comma-separated string.
     */
    public function getJurisdictionNamesAttribute(): string
    {
        if (empty($this->jurisdictions)) {
            return '';
        }
        return collect($this->jurisdictions)->pluck('display_name')->implode(', ');
    }

    /**
     * Get category names as a comma-separated string.
     */
    public function getCategoryNamesAttribute(): string
    {
        if (empty($this->doc_categories)) {
            return '';
        }
        return collect($this->doc_categories)->pluck('display_name')->implode(', ');
    }
}
