<?php

namespace App\Models;

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

class RegulationDocument extends Model
{
    protected $fillable = [
        'state_id', 'city_id', 'uploaded_by',
        'title', 'document_type', 'original_filename',
        'storage_path', 'file_hash', 'file_size_bytes',
        'extraction_status', 'extraction_error',
        'extracted_text_chunks', 'extracted_rules', 'ai_metadata',
        'review_status', 'reviewed_by', 'reviewed_at', 'review_notes',
        'rules_applied',
    ];

    protected $casts = [
        'extracted_text_chunks' => 'array',
        'extracted_rules'       => 'array',
        'ai_metadata'           => 'array',
        'reviewed_at'           => 'datetime',
        'rules_applied'         => 'boolean',
    ];

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

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

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

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

    /** Human-readable file size */
    public function getFileSizeHumanAttribute(): string
    {
        $bytes = $this->file_size_bytes;
        if ($bytes < 1024) return "{$bytes} B";
        if ($bytes < 1048576) return round($bytes / 1024, 1) . ' KB';
        return round($bytes / 1048576, 1) . ' MB';
    }

    /** Count of AI-extracted rules */
    public function getExtractedRulesCountAttribute(): int
    {
        return count($this->extracted_rules ?? []);
    }
}
