<?php

namespace App\Models;

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

class AiEmbedding extends Model
{
    protected $fillable = [
        'embeddable_type',
        'embeddable_id',
        'chunk_index',
        'content_text',
        'content_hash',
        'embedding',
        'metadata',
    ];

    protected $casts = [
        'embedding' => 'array',
        'metadata' => 'array',
    ];

    public function embeddable(): MorphTo
    {
        return $this->morphTo();
    }

    public static function needsUpdate(string $type, int $id, string $text, int $chunkIndex = 0): bool
    {
        $hash = md5($text);

        return ! static::where('embeddable_type', $type)
            ->where('embeddable_id', $id)
            ->where('chunk_index', $chunkIndex)
            ->where('content_hash', $hash)
            ->exists();
    }
}
