<?php

namespace App\Domain\Knowledge\Models;

use App\Domain\Agent\Models\Agent;
use App\Domain\Knowledge\Enums\KnowledgeBaseStatus;
use App\Domain\Shared\Traits\BelongsToTeam;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;

/**
 * @property string $id
 * @property string $team_id
 * @property string|null $agent_id
 * @property string $name
 * @property string|null $description
 * @property KnowledgeBaseStatus $status
 * @property int $chunks_count
 * @property Carbon|null $last_ingested_at
 * @property bool $ragflow_enabled
 * @property string|null $ragflow_dataset_id
 * @property string|null $ragflow_chunk_method
 * @property Carbon|null $ragflow_last_synced_at
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property Carbon|null $deleted_at
 * @property-read Agent|null $agent
 * @property-read Collection<int, KnowledgeChunk> $chunks
 */
class KnowledgeBase extends Model
{
    use BelongsToTeam, HasUuids, SoftDeletes;

    protected $fillable = [
        'team_id',
        'agent_id',
        'name',
        'description',
        'status',
        'chunks_count',
        'last_ingested_at',
        'ragflow_enabled',
        'ragflow_dataset_id',
        'ragflow_chunk_method',
        'ragflow_last_synced_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => KnowledgeBaseStatus::class,
            'chunks_count' => 'integer',
            'last_ingested_at' => 'datetime',
            'ragflow_enabled' => 'boolean',
            'ragflow_last_synced_at' => 'datetime',
        ];
    }

    public function isRagflowReady(): bool
    {
        return $this->ragflow_enabled && $this->ragflow_dataset_id !== null;
    }

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

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

    public function isReady(): bool
    {
        return $this->status === KnowledgeBaseStatus::Ready;
    }

    public function markIngesting(): void
    {
        $this->update(['status' => KnowledgeBaseStatus::Ingesting]);
    }

    public function markReady(int $chunksCount): void
    {
        $this->update([
            'status' => KnowledgeBaseStatus::Ready,
            'chunks_count' => $chunksCount,
            'last_ingested_at' => now(),
        ]);
    }

    public function markError(): void
    {
        $this->update(['status' => KnowledgeBaseStatus::Error]);
    }
}
