import {BotEvent, MedplumClient, resolveId} from '@medplum/core';
import {PractitionerRole, Practitioner} from '@medplum/fhirtypes';
import {isHcp, isPrescriberAdmin} from "../../utils/utils";

/*
This bot aims to update the Practitioner resource based on the PractitionerRole
associated with an organization. The process involves:

1. Retrieving the Organization referenced in the PractitionerRole.
2. If the Organization is part of another Organization, retrieve the parent Organization.
3. Depending on the code associated with the PractitionerRole:
   - If the code matches prescriber, the Practitioner is updated with the parent Organization as their account.
   - If the code matches hcp, the Practitioner is updated with the current Organization as their account.

Logs are provided for successful updates and errors to ensure traceability.
*/

export async function handler(medplum: MedplumClient, event: BotEvent<PractitionerRole>): Promise<any> {
    try {
        const organizationId = resolveId(event.input.organization);

        if (organizationId != null) {
            const practitionerRoleOrganization = await medplum.readResource('Organization', organizationId);
            const racineOrganizationId = resolveId(practitionerRoleOrganization.partOf);

            const practitionerId = resolveId(event.input.practitioner);
            if (practitionerId != null) {
                const existingPractitioner = await medplum.readResource('Practitioner', practitionerId);

                if (isPrescriberAdmin(event.input)) {
                    if (racineOrganizationId != null) {
                        const racineOrganization = await medplum.readResource('Organization', racineOrganizationId);
                        const updatedPractitioner = {
                            ...existingPractitioner,
                            meta: {
                                ...existingPractitioner.meta,
                                account: {
                                    reference: `Organization/${racineOrganization.id}`,
                                    display: racineOrganization.name
                                }
                            }
                        };
                        await medplum.updateResource<Practitioner>(updatedPractitioner);
                    }
                }

                if (isHcp(event.input)) {
                    const updatedPractitioner = {
                        ...existingPractitioner,
                        meta: {
                            ...existingPractitioner.meta,
                            account: {
                                reference: `Organization/${practitionerRoleOrganization.id}`,
                                display: practitionerRoleOrganization.name
                            }
                        }
                    };
                    await medplum.updateResource<Practitioner>(updatedPractitioner);
                }
                return true;

            } else {
                console.error('No practitioner ID found in the event input.');
                return false;
            }
        } else {
            console.error('No organization ID found in the event input.');
            return false;
        }
    } catch
        (error) {
        console.error('Error updating Practitioner assignment:', error);
        return false;
    }
}