<?php

namespace PortalPeople\virtualstock\models\db;

use yii\db\ActiveRecord;

/**
 * ActiveRecord for the `virtualstock_webhook_events` table.
 *
 * Stores a record for every inbound VirtualStock webhook push notification.
 * Events can be audited, replayed, or processed idempotently using this table.
 *
 * @property int         $id
 * @property string      $event          Event name, e.g. order.updated
 * @property string      $payload_json   Full raw payload JSON
 * @property string|null $signature      X-Virtualstock-Signature header value
 * @property bool        $verified       Whether the signature was verified
 * @property bool        $processed      Whether the event has been handled
 * @property string|null $error_message  Processing error message
 * @property int         $created_at
 * @property int|null    $processed_at
 */
class VirtualstockWebhookEvent extends ActiveRecord
{
    /** @inheritdoc */
    public static function tableName(): string
    {
        return '{{%virtualstock_webhook_events}}';
    }

    /** @inheritdoc */
    public function rules(): array
    {
        return [
            [['event', 'payload_json', 'created_at'], 'required'],
            [['event'], 'string', 'max' => 100],
            [['signature'], 'string', 'max' => 100],
            [['payload_json', 'error_message'], 'string'],
            [['verified', 'processed'], 'boolean'],
            [['created_at', 'processed_at'], 'integer'],
        ];
    }

    /** @inheritdoc */
    public function attributeLabels(): array
    {
        return [
            'id'            => 'ID',
            'event'         => 'Event',
            'payload_json'  => 'Payload JSON',
            'signature'     => 'Signature',
            'verified'      => 'Verified',
            'processed'     => 'Processed',
            'error_message' => 'Error Message',
            'created_at'    => 'Created At',
            'processed_at'  => 'Processed At',
        ];
    }

    // -------------------------------------------------------------------------
    // Helpers
    // -------------------------------------------------------------------------

    /**
     * Decode payload_json into an array (empty array if invalid).
     */
    public function getPayload(): array
    {
        return json_decode($this->payload_json, true) ?: [];
    }

    /**
     * Mark the event as processed (does not save — call save() after).
     */
    public function markProcessed(?string $errorMessage = null): void
    {
        $this->processed    = $errorMessage === null;
        $this->error_message = $errorMessage;
        $this->processed_at = time();
    }

    /**
     * Scope: unprocessed events ordered oldest-first.
     *
     * @return \yii\db\ActiveQuery
     */
    public static function findPending(): \yii\db\ActiveQuery
    {
        return static::find()
            ->where(['processed' => false])
            ->orderBy(['created_at' => SORT_ASC]);
    }

    /**
     * Scope: events of a specific type.
     *
     * @return \yii\db\ActiveQuery
     */
    public static function findByEvent(string $event): \yii\db\ActiveQuery
    {
        return static::find()->where(['event' => $event]);
    }
}
