<?php

namespace Espo\Modules\SmartAssistant\Hooks\Case;

use Espo\ORM\Entity;
use Espo\Core\InjectableFactory;
use Espo\Core\Utils\Log;
use Espo\Modules\SmartAssistant\Services\CaseMemoryService;

class CaseFieldChangeMemory
{
    private InjectableFactory $injectableFactory;
    private Log $log;

    public function __construct(InjectableFactory $injectableFactory, Log $log)
    {
        $this->injectableFactory = $injectableFactory;
        $this->log = $log;
    }

    public function afterSave(Entity $entity, array $options): void
    {
        if (!empty($options['skipSmartAssistantHook'])) return;

        $caseId = $entity->get('id');
        $service = $this->injectableFactory->create(CaseMemoryService::class);

        // Status change
        if ($entity->isAttributeChanged('status')) {
            $old = $entity->getFetched('status');
            $new = $entity->get('status');
            $service->createMemory(
                $caseId, 'timeline',
                "שינוי סטטוס: {$old} → {$new}",
                "סטטוס התיק שונה מ-\"{$old}\" ל-\"{$new}\"",
                'normal', 'auto',
                'Case', $caseId
            );
        }

        // Next hearing change
        if ($entity->isAttributeChanged('cNextHearing') && $entity->get('cNextHearing')) {
            $service->createMemory(
                $caseId, 'timeline',
                "דיון נקבע ל-" . $entity->get('cNextHearing'),
                "דיון הבא נקבע לתאריך: " . $entity->get('cNextHearing'),
                'high', 'auto',
                'Case', $caseId
            );
        }

        // Judge change
        if ($entity->isAttributeChanged('cJudge') && $entity->get('cJudge')) {
            $service->createMemory(
                $caseId, 'key_facts',
                "שופט: " . $entity->get('cJudge'),
                "השופט/ת בתיק: " . ($entity->get('cJudgeTitle') ?? '') . " " . $entity->get('cJudge'),
                'normal', 'auto',
                'Case', $caseId
            );
        }

        // Court change
        if ($entity->isAttributeChanged('cCourt') && $entity->get('cCourt')) {
            $service->createMemory(
                $caseId, 'key_facts',
                "בית משפט: " . $entity->get('cCourt'),
                "התיק נדון בבית המשפט: " . $entity->get('cCourt'),
                'normal', 'auto',
                'Case', $caseId
            );
        }
    }
}
