<?php

namespace Mtc\Plugins\CmsAuditLog\Src\Models;

use App\Casts\OptionalEncrypted;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * A single CMS change audit entry.
 *
 * @property int $id
 * @property string $action
 * @property int|null $page_id
 * @property string|null $page_title
 * @property int|null $admin_user_id
 * @property string|null $admin_user_name
 * @property string|null $ip_address
 * @property string|null $details JSON string
 */
class AuditEntry extends Model
{
    protected $table = 'cms_audit_log';

    const ACTION_PAGE_UPDATED = 'page_updated';
    const ACTION_PAGE_DELETED = 'page_deleted';
    const ACTION_PAGE_PUBLISHED = 'page_published';
    const ACTION_VERSION_SAVED = 'version_saved';
    const ACTION_CONTENT_UPDATED = 'content_updated';
    const ACTION_CONTENT_DELETED = 'content_deleted';
    const ACTION_CONTENT_STRUCTURE_SAVED = 'content_structure_saved';

    public static array $actions = [
        self::ACTION_PAGE_UPDATED => 'Page updated',
        self::ACTION_PAGE_DELETED => 'Page deleted',
        self::ACTION_PAGE_PUBLISHED => 'Page published',
        self::ACTION_VERSION_SAVED => 'Version saved',
        self::ACTION_CONTENT_UPDATED => 'Content field updated',
        self::ACTION_CONTENT_DELETED => 'Content field deleted',
        self::ACTION_CONTENT_STRUCTURE_SAVED => 'Content structure saved',
    ];

    protected $fillable = [
        'action',
        'page_id',
        'page_title',
        'admin_user_id',
        'admin_user_name',
        'ip_address',
        'details',
    ];

    protected $casts = [
        'admin_user_name' => OptionalEncrypted::class,
        'ip_address' => OptionalEncrypted::class,
        'details' => OptionalEncrypted::class,
    ];

    public function page(): BelongsTo
    {
        return $this->belongsTo(\Mtc\Cms\Models\Page::class, 'page_id');
    }

    public function getActionLabelAttribute(): string
    {
        return self::$actions[$this->action] ?? $this->action;
    }

    public function getDetailsArrayAttribute(): array
    {
        $details = json_decode($this->details ?? '', true);

        return is_array($details) ? $details : [];
    }
}
