<?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, bool $public = false): array
    {
        $workspace = WorkspacePayloadBuilder::build($container, $public);
        $currentUser = $workspace['user'] ?? null;
        $crm = $container->get('crm');
        $appLoginUrl = home_url('/plover-crm/login/');
        $hasCrmAccess = (bool) ($currentUser['access']['has_crm_access'] ?? false);

        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' => $hasCrmAccess,
                'nonce' => $hasCrmAccess ? wp_create_nonce('wp_rest') : '',
                'loginUrl' => $appLoginUrl,
                'logoutUrl' => home_url('/plover-crm/logout/'),
            ],
            'currentUser' => $currentUser,
            'workspace' => $workspace,
            'featureFlags' => [
                'wpHosted' => true,
                'cloudHosted' => false,
                'multiWorkspace' => false,
                'usesWordPressAuth' => true,
                'crmAvailable' => $crm && $crm->isAvailable(),
            ],
        ];
    }
}
