<?php

namespace SEOAIC\rest_api;

use Exception;
use SEOAIC\posts_mass_actions\FAQGenerate;
use SEOAIC\rest_api\http_resources\Result;
use SEOAIC\SEOAIC_SETTINGS;
use WP_REST_Request;
use WP_REST_Response;
use SEOAIC\traits\MassActionsWorkflow;

class FAQAPI extends AbstractAPI
{
    use MassActionsWorkflow;

    private $seoaic;

    public function __construct($seoaic)
    {
        $this->seoaic = $seoaic;

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/faq/prompt', [
                'methods' => 'GET',
                'callback' => [$this, 'getFAQPrompt'],
                'permission_callback' => [$this, 'validateNonce'],
            ]);

            register_rest_route('seoaic/v1', '/faq/generate', [
                'methods' => 'POST',
                'callback' => [$this, 'generate'],
                'permission_callback' => [$this, 'validateNonce'],
            ]);
            register_rest_route('seoaic/v1', '/faq/check-status', [
                'methods' => 'GET',
                'callback' => [$this, 'generateCheckStatus'],
                'permission_callback' => [$this, 'validateNonce'],
            ]);
        });
    }

    public function getFAQPrompt()
    {
        return new WP_REST_Response(Result::success(__FUNCTION__, 'OK', [
            'prompt' => SEOAIC_SETTINGS::getCustomFaqPrompt(),
        ]));
    }

    public function generate(WP_REST_Request $request)
    {
        $postID = $request->get_param('post_id');

        if (
            empty($postID)
            || !is_numeric($postID)
        ) {
            return new WP_REST_Response(Result::error('', esc_html__('Wrong post ID', 'seoaic')));
        }

        try {
            $instance = new FAQGenerate($this->seoaic);
            $instance->isAPI = true;
            $preparedData = $instance->prepareDataFromAPIRequest($request);
        } catch (Exception $e) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Error: ", "seoaic") . $e->getMessage()));
        }

        // $this->postsMassActionStop($instance, false);
        $result = $this->postsMassActionRun($instance, $preparedData);

        return new WP_REST_Response($result);
    }

    public function generateCheckStatus()
    {
        $instance = new FAQGenerate($this->seoaic);
        $data = $this->postsMassActionCheckStatusData($instance);

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), $data));
    }
}
