<?php

if (!defined('ABSPATH')) {
    exit;
}

class ACC_Runtime_Workflow_API {

    public static function init(): void {

        add_action(
            'rest_api_init',
            [self::class,'register_routes']
        );

    }

    public static function register_routes(): void {

        register_rest_route(
            'acc/v1',
            '/workflow/(?P<entity>[a-z0-9_]+)/(?P<id>\d+)/transition',
            [
                'methods'=>'POST',
                'callback'=>[self::class,'transition'],
                'permission_callback' => 'acc_jwt_check_permission',
            ]
        );

    }

    public static function transition(WP_REST_Request $req){

        global $wpdb;

        $entity = sanitize_key($req['entity']);
        $object_id = (int)$req['id'];
        $target_state = sanitize_key($req->get_param('state'));

        $states = $wpdb->prefix."erp_workflow_states";
        $instances = $wpdb->prefix."erp_workflow_instances";

        $state = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id FROM {$states} WHERE state_key=%s",
                $target_state
            )
        );

        if(!$state){

            return new WP_Error(
                'invalid_state',
                'State not found'
            );

        }

        $wpdb->update(
            $instances,
            ['state_id'=>$state->id],
            [
                'entity_key'=>$entity,
                'object_id'=>$object_id
            ]
        );

        return [
            'success'=>true,
            'state'=>$target_state
        ];

    }


}

ACC_Runtime_Workflow_API::init();
