<?php

namespace App\Http\Controllers\Portal;

use App\Domain\Shared\Services\SettingsService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

/**
 * The two files a platform fetches to verify that this domain and that app are
 * the same product.
 *
 * Both must be served as `application/json`, from the apex path, with **no
 * redirect** — a 301 to a canonical host is enough for the platform to refuse
 * verification, and it refuses silently: deep links simply open the browser
 * instead of the app, with nothing logged anywhere.
 *
 * They are routes rather than static files because the fingerprints are
 * per-tenant: every client has their own signing key and their own bundle id.
 * An unconfigured tenant returns an empty association rather than a 404, which
 * is the state that says "this domain is not linked to an app" instead of
 * "this domain is broken".
 */
class AppAssociationController extends Controller
{
    public function assetlinks(SettingsService $settings): JsonResponse
    {
        $package = (string) $settings->get('mobile_app.android_package');
        $fingerprints = array_values(array_filter(array_map(
            'trim',
            explode(',', (string) $settings->get('mobile_app.android_sha256_fingerprints'))
        )));

        if ($package === '' || $fingerprints === []) {
            return $this->json([]);
        }

        return $this->json([[
            'relation' => ['delegate_permission/common.handle_all_urls'],
            'target' => [
                'namespace' => 'android_app',
                'package_name' => $package,
                'sha256_cert_fingerprints' => $fingerprints,
            ],
        ]]);
    }

    public function appleAppSiteAssociation(SettingsService $settings): JsonResponse
    {
        $appId = (string) $settings->get('mobile_app.ios_app_id');   // TEAMID.bundle.id

        if ($appId === '') {
            return $this->json(['applinks' => ['details' => []]]);
        }

        return $this->json([
            'applinks' => [
                'details' => [[
                    'appIDs' => [$appId],
                    'components' => [
                        // Only the portal. Linking the whole domain would hand
                        // the ERP and the public website to the app as well.
                        ['/' => '/app/*', 'comment' => 'member portal'],
                    ],
                ]],
            ],
            'webcredentials' => ['apps' => [$appId]],
        ]);
    }

    private function json(array $payload): JsonResponse
    {
        return response()->json($payload, 200, [
            'Content-Type' => 'application/json',
        ], JSON_UNESCAPED_SLASHES);
    }
}
