<?php

namespace Modules\MedDocuments\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedDocuments\Entities\MeddocDocument;
use Modules\MedDocuments\Entities\MeddocShare;

/**
 * Secure expiring share links (spec §8). Creating a share returns a tokenized
 * public URL (/med-docs/shared/{token}). Revocation is a soft toggle.
 */
class ShareController extends MedDocBaseController
{
    /** Share-link modal (lists existing links + create form). */
    public function form($id)
    {
        $this->guard('meddoc.share');

        $document = $this->find($id);
        $shares = $document->shares()->orderByDesc('id')->get();
        $docs = $this->docs();

        return view('meddocuments::shares.form', compact('document', 'shares', 'docs'));
    }

    public function store(Request $request, $id)
    {
        $this->guard('meddoc.share');

        $data = $this->validate($request, [
            'days' => 'nullable|integer|min:1|max:365',
        ]);

        try {
            $document = $this->find($id);
            $share = $this->docs()->share($document, $data['days'] ?? null, $this->userId());

            return $this->ok(__('meddocuments::lang.share_created'), [
                'url'   => $this->docs()->shareUrl($share),
                'token' => $share->token,
            ]);
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    public function revoke($id)
    {
        $this->guard('meddoc.share');

        try {
            $share = MeddocShare::where('business_id', $this->businessId())->findOrFail($id);
            $share->update(['revoked_at' => now()]);

            return $this->ok(__('meddocuments::lang.share_revoked'));
        } catch (\Exception $e) {
            return $this->fail();
        }
    }

    protected function find($id): MeddocDocument
    {
        return MeddocDocument::forBusiness($this->businessId())
            ->where('status', '!=', 'deleted')
            ->findOrFail($id);
    }
}
