<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Common\Permissions;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Core\Services\PipelineTemplateRegistry;
use PloverCRM\Core\Services\WorkspaceSetupService;
use WP_REST_Request;

/**
 * Workspace setup / onboarding endpoint.
 */
class SetupEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/setup';
    }

    public function getMethod()
    {
        return ['GET', 'PUT'];
    }

    public function handle(WP_REST_Request $request)
    {
        if ($request->get_method() === 'GET') {
            return $this->success([
                'setup' => WorkspaceSetupService::getState(),
                'stageTemplates' => PipelineTemplateRegistry::getTemplates(),
            ]);
        }

        if (!Permissions::isSuperAdmin()) {
            return $this->error(
                'You do not have permission to manage workspace setup.',
                403,
                'workspace_setup_manage_permission_denied'
            );
        }

        $payload = $request->get_json_params();
        $payload = is_array($payload) ? ($payload['setup'] ?? $payload) : [];

        $updatedState = WorkspaceSetupService::updateState(
            is_array($payload) ? $payload : []
        );

        if (is_wp_error($updatedState)) {
            return $updatedState;
        }

        return $this->success([
            'setup' => $updatedState,
            'stageTemplates' => PipelineTemplateRegistry::getTemplates(),
            'message' => !empty($updatedState['isCompleted'])
                ? 'Workspace setup completed.'
                : 'Workspace setup updated.',
        ]);
    }
}
