<?php

namespace PortalPeople\netsuite\controllers\api;

use Yii;
use yii\rest\Controller;
use yii\filters\VerbFilter;
use PortalPeople\netsuite\models\NetsuiteDecoder;

/**
 * Handles inbound requests from NetSuite SuiteScript webhooks.
 */
class NetsuiteController extends Controller
{
    /**
     * CSRF validation is not applicable for inbound webhook endpoints.
     */
    public $enableCsrfValidation = false;

    /**
     * {@inheritdoc}
     */
    public function behaviors(): array
    {
        $behaviors = parent::behaviors();

        $behaviors['verbs'] = [
            'class'   => VerbFilter::class,
            'actions' => [
                'updateorder' => ['POST'],
            ],
        ];

        return $behaviors;
    }

    /**
     * Receive a Sales Order change payload from NetSuite PP_Order_Change.
     *
     * Decodes the payload via NetsuiteDecoder (handles json, json+gzip,
     * json+aes-cbc and json+gzip+aes-cbc formats) then logs the decoded
     * data for inspection.
     *
     * @return array JSON response.
     */
    public function actionUpdateorder(): array
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $rawBody = Yii::$app->request->rawBody;

        $decoder = new NetsuiteDecoder();
        $data    = $decoder->decode($rawBody);

        if ($data === null) {
            Yii::$app->response->statusCode = 400;
            return ['status' => 'error', 'message' => 'Failed to decode payload'];
        }

        Yii::warning($data, 'netsuite.updateorder');

        return ['status' => 'ok'];
    }
}
