<?php

namespace PloverCRM\Core\Services;

use PloverCRM\Core\Container;

/**
 * Builds the frontend host bootstrap contract for the standalone CRM app.
 */
class FrontendBootstrapBuilder
{
    public static function build(Container $container): array
    {
        $workspace = WorkspacePayloadBuilder::build($container);
        $currentUser = $workspace['user'] ?? null;
        $crm = $container->get('crm');

        return [
            'version' => 1,
            'hostMode' => 'wordpress',
            'deployment' => 'selfHosted',
            'appVersion' => defined('PLOVER_CRM_PLUGIN_VERSION') ? PLOVER_CRM_PLUGIN_VERSION : 'dev',
            'site' => [
                'name' => get_bloginfo('name'),
                'url' => get_site_url(),
                'adminUrl' => admin_url(),
                'appUrl' => home_url('/plover-crm/'),
            ],
            'api' => [
                'restRoot' => untrailingslashit(rest_url()),
                'crmV1Base' => untrailingslashit(rest_url('plover-crm/v1')),
                'crmV2Base' => untrailingslashit(rest_url('plover-crm/v2')),
                'bootstrapUrl' => untrailingslashit(rest_url('plover-crm/v2/bootstrap')),
            ],
            'auth' => [
                'mode' => 'wordpressCookie',
                'isAuthenticated' => is_user_logged_in(),
                'nonce' => is_user_logged_in() ? wp_create_nonce('wp_rest') : '',
                'loginUrl' => wp_login_url(home_url('/plover-crm/')),
                'logoutUrl' => wp_logout_url(home_url('/plover-crm/')),
            ],
            'currentUser' => $currentUser,
            'workspace' => $workspace,
            'featureFlags' => [
                'wpHosted' => true,
                'cloudHosted' => false,
                'multiWorkspace' => false,
                'usesWordPressAuth' => true,
                'crmAvailable' => $crm && $crm->isAvailable(),
            ],
        ];
    }
}
