<?php

namespace Tests\Support\Traits;

use App\Models\Patient\PatientModel;
use Faker\Factory;

trait CreatesPatients
{
    protected function createTestPatient(array $overrides = []): int
    {
        $faker = Factory::create('id_ID');
        $patientPayload = array_merge([
            'PatientID'      => 'PAT' . $faker->numerify('##########'),
            'AlternatePID'   => 'ALT' . $faker->numerify('##########'),
            'Prefix'         => $faker->title,
            'NameFirst'      => 'Test',
            'NameMiddle'     => $faker->firstName,
            'NameLast'       => 'Patient',
            'Suffix'         => 'S.Kom',
            'Sex'            => (string) $faker->numberBetween(5, 6),
            'PlaceOfBirth'   => $faker->city,
            'Birthdate'      => $faker->date('Y-m-d'),
            'ZIP'            => $faker->postcode,
            'Street_1'       => $faker->streetAddress,
            'City'           => $faker->city,
            'Province'       => $faker->state,
            'EmailAddress1'  => 'test.' . $faker->unique()->userName . '@example.com',
            'Phone'          => $faker->numerify('08##########'),
            'MobilePhone'    => $faker->numerify('08##########'),
            'Race'           => (string) $faker->numberBetween(175, 205),
            'Country'        => (string) $faker->numberBetween(221, 469),
            'MaritalStatus'  => (string) $faker->numberBetween(8, 15),
            'Religion'       => (string) $faker->numberBetween(206, 212),
            'Ethnic'         => (string) $faker->numberBetween(213, 220),
            'Citizenship'    => 'WNI',
            'isDead' => (string) $faker->numberBetween(0, 1),
            'PatIdt' => [
                'IdentifierType' => 'ID',
                'Identifier'     => $faker->numerify('################')
            ],
            'PatAtt' => [
                [ 'Address' => '/api/upload/' . $faker->uuid . '.jpg' ]
            ],
            'PatCom' => $faker->sentence,
        ], $overrides);

        if ($patientPayload['isDead'] === '1') {
            $patientPayload['DeathDateTime'] = $faker->date('Y-m-d H:i:s');
        } else {
            $patientPayload['DeathDateTime'] = null;
        }

        $patientModel = new PatientModel();
        $internalPID = $patientModel->createPatient($patientPayload);
        if (!$internalPID) {
            throw new \RuntimeException('Failed to insert test patient');
        }

        return $internalPID;
    }
}
