<?php

namespace App\Services\Care;

use App\Models\Organization;
use App\Models\Patient;
use App\Models\Visit;
use App\Services\Care\Workflow\WorkflowEngine;

class VisitService
{
    public function __construct(
        protected CareFeatures $features,
        protected WorkflowEngine $workflows,
    ) {}

    public function checkIn(
        Organization $organization,
        string $ownerRef,
        Patient $patient,
        int $branchId,
        ?string $actorRef = null,
    ): Visit {
        $visit = Visit::create([
            'owner_ref' => $ownerRef,
            'organization_id' => $organization->id,
            'branch_id' => $branchId,
            'patient_id' => $patient->id,
            'status' => Visit::STATUS_OPEN,
            'checked_in_at' => now(),
            'checked_in_by' => $actorRef,
        ]);

        AuditLogger::record($ownerRef, 'visit.checked_in', $organization->id, $actorRef, Visit::class, $visit->id);

        if ($this->features->enabled($organization, CareFeatures::WORKFLOW_ENGINE)) {
            $this->workflows->start($visit);
        }

        return $visit;
    }

    public function complete(Visit $visit, string $ownerRef, ?string $actorRef = null): Visit
    {
        $visit->refresh();

        app(VisitPlacementService::class)->dischargePlacement($visit, $ownerRef, $actorRef, 'Visit completed');

        $visit->refresh();

        $visit->update([
            'status' => Visit::STATUS_COMPLETED,
            'completed_at' => now(),
        ]);

        AuditLogger::record($ownerRef, 'visit.completed', $visit->organization_id, $actorRef, Visit::class, $visit->id);

        return $visit;
    }
}
