<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Services\AccountStorageResolver;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Server-to-server endpoint the Azure Function App (Python OCR pipeline) calls
 * to get a per-account storage credential for a document, whichever backend
 * that account uses (SharePoint / Server / Google Drive). PHP keeps every
 * encrypted secret + APP_KEY; the function app only ever receives a
 * short-lived token or a plain server credential — see
 * AccountStorageResolver::resolveTokenContext for the exact shape per
 * backend. Gated by a shared secret header (not Sanctum — there is no user in
 * the OCR pipeline).
 */
class InternalStorageController extends Controller
{
    public function __construct(private AccountStorageResolver $storage) {}

    // POST /api/v1/internal/storage-context   { "document_id": "<guid>" }
    public function resolve(Request $request): JsonResponse
    {
        // Locked in production; open on local dev (localhost isn't exposed), so
        // the pipeline can be tested end-to-end without configuring a secret.
        if (!app()->environment('local')) {
            $expected = (string) config('services.internal.storage_secret');
            $provided = (string) $request->header('X-Internal-Secret', '');
            if ($expected === '' || !hash_equals($expected, $provided)) {
                return response()->json(['success' => false, 'message' => 'Unauthorized.'], 401);
            }
        }

        $data = $request->validate(['document_id' => 'required|uuid']);

        // READ context — the credential the pipeline uses to fetch the source
        // file (dispatches on the document's cr6f2_documentlink scheme).
        $context = $this->storage->resolveContextForDocument($data['document_id']);

        // MIRROR context — the client's own backend (Server/SFTP-FTP or Google
        // Drive) the pipeline pushes copies INTO (split children, SplitOriginal,
        // rotation), so the client folder stays a live mirror of SharePoint.
        // Independent of the read context: a dual-write document reads from SYHC
        // SharePoint (has_account_storage=false) yet still mirrors to the client.
        $mirror = $this->storage->resolveClientMirrorContextForDocument($data['document_id']);

        $response = ['success' => true, 'has_account_storage' => (bool) $context];
        if ($context) {
            $response = array_merge($response, $context);
        }
        if ($mirror) {
            $response['client_mirror'] = $mirror;
        }

        return response()->json($response);
    }
}
