<?php

namespace Modules\MedPortal\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Modules\MedPortal\Entities\MportalTelemedicine;

/**
 * Telemedicine join-link — STUB (SIFA Phase 8, BACKLOG).
 *
 * "Generate link" stores a PLACEHOLDER join_url on a ClinicCore appointment.
 * There is NO real video integration (no Zoom/Meet/Teams API call, no WebRTC
 * signalling, no waiting room). Delivered here: the data layer + link lifecycle
 * only. Reachable from the record-release / health screens; guarded by
 * mportal.manage.
 */
class TelemedicineController extends MedPortalBaseController
{
    public function store(Request $request)
    {
        $this->guard('mportal.manage');

        $data = $this->validate($request, [
            'appointment_id' => 'required|integer',
            'provider'       => 'nullable|in:' . implode(',', MportalTelemedicine::PROVIDERS),
        ]);

        try {
            $businessId = $this->businessId();
            $provider   = $data['provider'] ?? 'builtin';

            // STUB: placeholder URL only — real integration is backlog.
            $base = rtrim((string) config('medportal.telemedicine.placeholder_base'), '/');
            $joinUrl = $base . '/' . Str::random(12);

            $row = MportalTelemedicine::updateOrCreate(
                ['business_id' => $businessId, 'appointment_id' => (int) $data['appointment_id']],
                [
                    'join_url'   => $joinUrl,
                    'provider'   => $provider,
                    'status'     => 'scheduled',
                    'created_by' => $this->userId(),
                ]
            );

            return $this->ok(__('medportal::lang.telemedicine_link_generated'), [
                'join_url' => $row->join_url,
                'note'     => __('medportal::lang.telemedicine_stub_note'),
            ]);
        } catch (\Throwable $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }
}
