<?php

namespace Modules\MedDocuments\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\MedDocuments\Entities\MeddocShare;
use Modules\MedDocuments\Services\MedDocuments;
use Modules\MedDocuments\Services\Watermarker;

/**
 * Public tokenized share access (no login, spec §8). Expiry + revocation are
 * checked on every hit, the access is logged to meddoc_access_logs (user_id
 * null = public), and ONLY a watermarked view is served — never a raw download,
 * never the original.
 */
class PublicShareController extends Controller
{
    public function __construct(
        protected MedDocuments $docs,
        protected Watermarker $watermarker
    ) {
    }

    /** Landing page for a shared document (embeds the watermarked view). */
    public function show(Request $request, string $token)
    {
        $share = $this->validShareOr404($token);
        $document = $share->document;

        if (! $document || $document->status === 'deleted') {
            abort(404);
        }

        $version = $this->docs->versionToServe($document);
        if (! $version) {
            abort(404);
        }

        $share->increment('access_count');
        $this->docs->log($document, 'view', $version->id, null);

        return view('meddocuments::public.shared', [
            'document' => $document,
            'version'  => $version,
            'token'    => $token,
            'viewUrl'  => route('meddoc.shared.view', ['token' => $token]),
        ]);
    }

    /** Watermarked inline stream for the shared document. */
    public function view(Request $request, string $token)
    {
        $share = $this->validShareOr404($token);
        $document = $share->document;

        if (! $document || $document->status === 'deleted') {
            abort(404);
        }

        $version = $this->docs->versionToServe($document);
        if (! $version) {
            abort(404);
        }

        $bytes = $this->docs->bytes($version);
        if ($bytes === null) {
            abort(404);
        }

        $caption = Watermarker::caption(__('meddocuments::lang.shared_view'));
        $this->docs->log($document, 'view', $version->id, null);

        if ($version->isImage()) {
            $out = $this->watermarker->image($bytes, $caption);

            return response($out, 200, [
                'Content-Type'        => 'image/png',
                'Content-Disposition' => 'inline; filename="shared.png"',
                'Cache-Control'       => 'private, no-store',
            ]);
        }

        if ($version->isPdf()) {
            $stamped = $this->watermarker->pdf($bytes, $caption);
            if ($stamped !== null) {
                return response($stamped, 200, [
                    'Content-Type'        => 'application/pdf',
                    'Content-Disposition' => 'inline; filename="shared.pdf"',
                    'Cache-Control'       => 'private, no-store',
                ]);
            }
        }

        // Non-image/non-pdf (or PDF stamp failure): render the HTML viewer with
        // a CSS watermark overlay — never expose the raw bytes on the public route.
        return view('meddocuments::public.viewer', [
            'document'    => $document,
            'version'     => $version,
            'caption'     => $caption,
            'sourceUrl'   => null,   // no raw source on the public route
            'canOriginal' => false,
            'isPublic'    => true,
        ]);
    }

    /**
     * Resolve a valid share by token or 404. Invalid = unknown / revoked /
     * expired (all indistinguishable to the visitor).
     */
    protected function validShareOr404(string $token): MeddocShare
    {
        $share = MeddocShare::where('token', $token)->first();

        if (! $share || ! $share->isValid()) {
            abort(404);
        }

        return $share;
    }
}
