<?php

namespace PortalPeople\virtualstock\models\db;

use yii\db\ActiveRecord;

/**
 * ActiveRecord for the `virtualstock_api_log` table.
 *
 * Stores a structured record for every API request made via `VirtualStockClient`.
 * Populated by `ApiLogger` when a DB log target is in use.
 *
 * @property int         $id
 * @property string      $method           HTTP method (GET, POST, PATCH, DELETE)
 * @property string      $uri              Request URI relative to base URL
 * @property int|null    $status_code      HTTP response status code
 * @property int|null    $duration_ms      Request duration in milliseconds
 * @property string|null $request_body     Request body payload (may be null)
 * @property string|null $response_body    Response body (may be null)
 * @property string|null $error_class      Exception class name on failure
 * @property string|null $error_message    Exception message on failure
 * @property int         $created_at
 */
class VirtualstockApiLog extends ActiveRecord
{
    /** @inheritdoc */
    public static function tableName(): string
    {
        return '{{%virtualstock_api_log}}';
    }

    /** @inheritdoc */
    public function rules(): array
    {
        return [
            [['method', 'uri', 'created_at'], 'required'],
            [['method'], 'string', 'max' => 10],
            [['uri'], 'string', 'max' => 500],
            [['status_code', 'duration_ms', 'created_at'], 'integer'],
            [['request_body', 'response_body', 'error_message'], 'string'],
            [['error_class'], 'string', 'max' => 200],
        ];
    }

    /** @inheritdoc */
    public function attributeLabels(): array
    {
        return [
            'id'            => 'ID',
            'method'        => 'Method',
            'uri'           => 'URI',
            'status_code'   => 'Status Code',
            'duration_ms'   => 'Duration (ms)',
            'request_body'  => 'Request Body',
            'response_body' => 'Response Body',
            'error_class'   => 'Error Class',
            'error_message' => 'Error Message',
            'created_at'    => 'Created At',
        ];
    }

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

    /**
     * True if this entry represents a failed request.
     */
    public function isError(): bool
    {
        return $this->error_class !== null || ($this->status_code !== null && $this->status_code >= 400);
    }

    /**
     * Scope: only error entries.
     *
     * @return \yii\db\ActiveQuery
     */
    public static function findErrors(): \yii\db\ActiveQuery
    {
        return static::find()->where(['IS NOT', 'error_class', null]);
    }

    /**
     * Decode response_body into an array (empty array if null/invalid).
     */
    public function getResponseData(): array
    {
        if ($this->response_body === null || $this->response_body === '') {
            return [];
        }
        return json_decode($this->response_body, true) ?: [];
    }
}
