<?php

namespace Mtc\Plugins\CmsAuditLog\Src\Observers;

use Mtc\Cms\Models\PageListItemData;
use Mtc\Plugins\CmsAuditLog\Src\AuditLogger;
use Mtc\Plugins\CmsAuditLog\Src\Models\AuditEntry;

/**
 * Records old/new values whenever a CMS content field is edited.
 *
 * Only `updated` is observed on purpose: page version saves clone
 * every content row, so logging `created` would flood the audit log
 * with rows that are not admin edits.
 */
class PageListItemDataObserver
{
    public function updated(PageListItemData $data): void
    {
        if (!$data->wasChanged('value')) {
            return;
        }

        AuditLogger::log(
            AuditEntry::ACTION_CONTENT_UPDATED,
            !empty($data->page_id) ? (int) $data->page_id : null,
            null,
            [
                'page_list_item_data_id' => $data->id,
                'field_name' => $data->name,
                'language' => $data->language,
                'old_value' => AuditLogger::truncateValue($data->getOriginal('value')),
                'new_value' => AuditLogger::truncateValue($data->value),
            ]
        );
    }

    public function deleted(PageListItemData $data): void
    {
        AuditLogger::log(
            AuditEntry::ACTION_CONTENT_DELETED,
            !empty($data->page_id) ? (int) $data->page_id : null,
            null,
            [
                'page_list_item_data_id' => $data->id,
                'field_name' => $data->name,
                'language' => $data->language,
                'old_value' => AuditLogger::truncateValue($data->value),
            ]
        );
    }
}
