import { BaseAdapter, FACE_ASSIGNMENT_EVENT, LoggerPort, QueueMessageType, QueueMessageTypes } from '@humand-packages/common';
import { Service } from 'typedi';
import { TimeTrackingFaceAssignmentQueueConsumerPort } from '../../business/ports/timeTrackingFaceAssignmentQueueConsumerPort';
import TimeTrackingFaceAssignmentService from '../../business/services/timeTracking/timeTrackingFaceAssignment';

@Service()
export class TimeTrackingFaceAssignmentQueueConsumerAdapter extends BaseAdapter implements TimeTrackingFaceAssignmentQueueConsumerPort {
    constructor(
        private readonly faceAssignmentService: TimeTrackingFaceAssignmentService,
        private readonly logger: LoggerPort,
    ) {
        super();
    }

    public handleFaceAssignment = async (message: QueueMessageType<QueueMessageTypes.TIME_TRACKING_FACE_ASSIGNMENT>): Promise<void> => {
        const body = message.messageBody;
        if (!body) {
            this.logger.warn({ messageId: message.messageId }, '[face-assignment-consumer] received empty body, dropping');
            return;
        }
        switch (body.event) {
            case FACE_ASSIGNMENT_EVENT.CDC_TIME_TRACKING_USER_CREATED:
                await this.faceAssignmentService.handleUserCreation(body.instanceId, body.userId);
                return;
            case FACE_ASSIGNMENT_EVENT.FACE_CONFIG_UPDATED:
                await this.faceAssignmentService.handleUpdateUserFaces(body.instanceId, body.userIds);
                return;
            case FACE_ASSIGNMENT_EVENT.SITE_USERS_ASSIGNED:
            case FACE_ASSIGNMENT_EVENT.REGION_SITE_USERS_ASSIGNED:
                await this.faceAssignmentService.handleUserAssignmentToSites(body.instanceId, body.userIds);
                return;
            case FACE_ASSIGNMENT_EVENT.CDC_TIME_TRACKING_USER_DELETED:
                await this.faceAssignmentService.handleUserDeletion(body.instanceId, body.userId);
                return;
            case FACE_ASSIGNMENT_EVENT.SITE_USERS_UNASSIGNED:
                await this.faceAssignmentService.handleUserUnassignmentFromSite(body.instanceId, body.siteId, body.userIds);
                return;
            case FACE_ASSIGNMENT_EVENT.REGION_USERS_UNASSIGNED:
                await this.faceAssignmentService.handleUserUnassignmentFromRegion(body.instanceId, body.regionId, body.userIds);
                return;
            case FACE_ASSIGNMENT_EVENT.FACE_CONFIG_DELETED:
                await this.faceAssignmentService.handleUserFaceConfigDeleted(body.instanceId, body.userIds);
                return;
            case FACE_ASSIGNMENT_EVENT.SITE_DELETED:
                await this.faceAssignmentService.deleteSitesCollections(body.instanceId, [body.siteId]);
                return;
            case FACE_ASSIGNMENT_EVENT.REGION_DELETED:
                await this.faceAssignmentService.deleteSitesCollections(body.instanceId, body.siteIds);
                return;
        }
    };
}
