<?php

namespace App\Services;

use App\Exceptions\ApiHttpException;
use App\Models\Backoffice\Doctor;
use App\Models\Backoffice\Patient;
use Illuminate\Support\Str;

class PatientService
{
    public function generatePatientToken($patientId)
    {
        $patient = Patient::findOrFail($patientId);
        if(empty($patient)){
            throw new ApiHttpException(404, 'patient_not_found');
        }

        $patient->token = Str::random(60);
        $patient->save();

        return $patient;
    }

    public function checkPatientToken($data): ?Patient
    {
        $patient = Patient::where('token', $data['token'])->first();

        if(empty($patient)){
            throw new ApiHttpException(404, 'patient_not_found');
        }

        if ($patient->token === $data['token']) {
            return $patient;
        }
        return null;
    }

    public function createPatient($data)
    {
        // Check if a patient with this device_id already exists
        $existingPatient = Patient::where('device_id', $data['deviceId'])->first();

        if ($existingPatient) {
            // If exists, return the existing patient with their current token
            return $existingPatient;
        }

        // Verify that the doctor code exists and is active
        $doctor = Doctor::where('code', $data['doctorCode'])
            ->where('status', Doctor::STATUS_ACTIVE)
            ->first();

        if (empty($doctor)) {
            throw new ApiHttpException(404, 'doctor_not_found', ['code' => $data['doctorCode']]);
        }

        // Create new patient
        $patient = new Patient();
        $patient->doctor_id = $doctor->id;
        $patient->device_id = $data['deviceId'];
        $patient->save();

        // Generate token for the new patient
        $patient = $this->generatePatientToken($patient->id);
        return $patient;
    }

    public function getPatient($patientId)
    {
        $patient = Patient::find($patientId);
        return $patient;
    }
}
