<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Appointment;
use App\Services\Care\AppointmentPatientNotifier;
use App\Services\Care\AuditLogger;
use App\Services\Meet\MeetClient;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class AppointmentMeetController extends Controller
{
    use ScopesToAccount;

    public function schedule(Request $request, Appointment $appointment, AppointmentPatientNotifier $notifier): RedirectResponse
    {
        $this->authorizeAbility($request, 'appointments.manage');
        $this->authorizeOwner($request, $appointment);

        if ($appointment->meet_join_url) {
            return redirect()->route('care.appointments.show', $appointment)
                ->with('success', 'Video visit is already scheduled.');
        }

        $appointment->loadMissing('patient');
        $patient = $appointment->patient;
        $owner = $this->ownerRef($request);
        $organization = $this->organization($request);
        $user = $request->user();

        $inviteEmails = [];
        if ($notifier->shouldInvitePatientEmailViaMeet($organization)) {
            $inviteEmails = array_values(array_filter([(string) $patient->email]));
        }

        $response = MeetClient::for($owner)->createRoom([
            'title' => 'Video visit — '.$patient->fullName(),
            'description' => $appointment->reason,
            'scheduled_at' => ($appointment->scheduled_at ?? now()->addHour())->toIso8601String(),
            'duration_minutes' => 30,
            'branch_id' => $appointment->branch_id,
            'host_name' => $user?->name,
            'host_email' => $user?->email,
            'source' => [
                'app' => 'care',
                'entity_type' => 'appointment',
                'entity_id' => $appointment->uuid,
            ],
            'invite_emails' => $inviteEmails,
        ]);

        $appointment->update([
            'meet_room_uuid' => data_get($response, 'room.uuid'),
            'meet_join_url' => data_get($response, 'join_url'),
        ]);

        AuditLogger::record($owner, 'appointment.meet_scheduled', $appointment->organization_id, $owner, Appointment::class, $appointment->id);

        $notifier->notifyVideoScheduled($organization, $appointment->fresh(['patient', 'branch']));

        return redirect()->route('care.appointments.show', $appointment)
            ->with('success', 'Video visit scheduled.'.($this->notifyHint($organization, $notifier)));
    }

    public function start(Request $request, Appointment $appointment, AppointmentPatientNotifier $notifier): RedirectResponse
    {
        $this->authorizeAbility($request, 'consultations.manage');
        $this->authorizeOwner($request, $appointment);

        $owner = $this->ownerRef($request);
        $organization = $this->organization($request);
        $appointment->loadMissing('patient');
        $user = $request->user();
        $createdRoom = false;

        if (! $appointment->meet_room_uuid) {
            $inviteEmails = [];
            if ($notifier->shouldInvitePatientEmailViaMeet($organization)) {
                $inviteEmails = array_values(array_filter([(string) $appointment->patient->email]));
            }

            $response = MeetClient::for($owner)->createRoom([
                'title' => 'Video visit — '.$appointment->patient->fullName(),
                'description' => $appointment->reason,
                'host_name' => $user?->name,
                'host_email' => $user?->email,
                'source' => [
                    'app' => 'care',
                    'entity_type' => 'appointment',
                    'entity_id' => $appointment->uuid,
                ],
                'invite_emails' => $inviteEmails,
            ]);

            $appointment->update([
                'meet_room_uuid' => data_get($response, 'room.uuid'),
                'meet_join_url' => data_get($response, 'join_url'),
            ]);
            $createdRoom = true;
        }

        if ($createdRoom) {
            $notifier->notifyVideoScheduled($organization, $appointment->fresh(['patient', 'branch']));
        }

        $start = MeetClient::for($owner)->startRoom((string) $appointment->meet_room_uuid, $owner);

        return redirect()->away((string) (data_get($start, 'join_url') ?: $appointment->meet_join_url));
    }

    private function notifyHint($organization, AppointmentPatientNotifier $notifier): string
    {
        $sms = $notifier->organizationWants($organization, AppointmentPatientNotifier::SETTING_VIDEO_SMS);
        $email = $notifier->organizationWants($organization, AppointmentPatientNotifier::SETTING_VIDEO_EMAIL);

        if ($sms || $email) {
            return ' Patient notification settings will be applied.';
        }

        return ' Enable video notifications in Settings to alert the patient.';
    }
}
